当键盘出现时移动文本字段会覆盖(Swift)中的顶部文本字段



我第一次遇到屏幕底部文本字段的问题是因为键盘会覆盖它们。既然我解决了那个问题,我就有了一个新问题。当我试图在屏幕顶部的文本字段中输入文本时,屏幕会上升,不让我看到我正在键入的内容。

我想我最理想的做法是改变键盘向上推屏幕的程度。下面是我用于初始更改的代码。

我两周前刚开始学习开发,所以我仍然熟悉所有的语法和函数。

var kbHeight: CGFloat!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize =  (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
kbHeight = keyboardSize.height
self.animateTextField(true)
}
}
}
func keyboardWillHide(notification: NSNotification) {
self.animateTextField(false)
}
func animateTextField(up: Bool) {
var movement = (up ? -kbHeight : kbHeight)
UIView.animateWithDuration(0.3, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
})
}

这是的建议

而不是设置视图的框架。将视图放在UIScrollView中。然后在您的键盘WillShow和键盘WillHide方法中相应地调整滚动视图框。

并使用textfield委托方法中的"scrollRectToVisible"设置滚动视图的内容偏移量。

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
CGRect rectText = textField.frame;
self.scrollVIew scrollRectToVisible:rectText animated:TRUE];
}

最新更新