我首先遇到屏幕底部文本字段的问题,因为键盘会覆盖它们。既然我解决了那个问题,我就有了一个新问题。当我尝试在屏幕顶部的文本字段中输入文本时,屏幕升起并且不让我看到我正在输入的内容。
我想我最想做的是改变键盘将屏幕向上推的程度。下面是我用于初始更改的代码。
我两周前才开始学习开发,所以我仍然熟悉所有的语法和函数。
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)
})
}
最佳答案
这是一个建议
而不是设置 View 的框架。将 View 放在 UIScrollView 中。 然后在您的 keyboardWillShow 和 keyboardWillHide 方法中相应地调整 ScrollView 框架。
并使用文本字段委托(delegate)方法中的“scrollRectToVisible”设置 ScrollView 的内容偏移量。
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
CGRect rectText = textField.frame;
self.scrollVIew scrollRectToVisible:rectText animated:TRUE];
}
关于ios - 出现键盘时移动文本字段会覆盖(Swift)中的顶部文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29987581/