键盘问题移动视图。(键盘大小&& view move back issue)

时间:2017-10-21 03:20:24

标签: ios swift uitextfield uikeyboard

UIView中有几个TextField。我想在用户编辑TextField时向上移动视图。然后我尝试引用Move view with keyboard using Swift

我的核心代码如下:

//MARK: Properties
@IBOutlet weak var userAccountTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!

//MARK: Callback
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}

func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
            if self.view.frame.origin.y == 0{
                //self.view.frame.origin.y -= keyboardSize.height
                self.view.frame.origin.y -= 150
            }
        }
    }

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
        if self.view.frame.origin.y != 0{
            //self.view.frame.origin.y += keyboardSize.height
            self.view.frame.origin.y += 150
        }
    }

}

有两个问题:

1.使用隐藏键盘的keyboardSize.height比keyboardSize.height大,并显示键盘。然后键盘隐藏后会出现黑色字段。所以现在我必须使用一个常数。

2.键盘显示后视图向上移动,它很好。但是当我键入一些字符或者我点击其他TextFiled时,视图再次向下移动。如果我将这些TextFields放入ScrollView.But我不知道为什么。如下图所示: enter image description here

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你的“viewDidLoad”方法包含一个错误,你必须添加而不是删除观察者,你必须在“viewWillDisappear”中删除它

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)    
}