当键盘出现时尝试移动视图 - 一些错误

问题描述 投票:0回答:2

我试图向上移动我的整个视图,以便能够看到用户在文本字段中输入的内容。但是,它在我想要的时候第一次完美运行。但是,当单击键盘上的返回键(以解除它),然后单击文本字段时,我会将键盘略微放在文本字段上,而不是像第一次那样得到相同的结果。为什么是这样?

这是我的代码:

@IBOutlet weak var commentTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    commentTextField.delegate = self

    //Keyboard listeners
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

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

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    commentTextField.resignFirstResponder()
    return true
}    
ios swift uitextfield nsnotificationcenter uikeyboard
2个回答
2
投票

更换

UIKeyboardFrameBeginUserInfoKey

UIKeyboardFrameEndUserInfoKey

1
投票

你错过了变量。

UIKeyboardFrameBeginUserInfoKey

包含CGRect的NSValue对象的键,用于标识屏幕坐标中键盘的起始帧矩形。框架矩形反映了设备的当前方向。

UIKeyboardFrameEndUserInfoKey

包含CGRect的NSValue对象的键,用于标识屏幕坐标中键盘的结束帧矩形。框架矩形反映了设备的当前方向。

因此,您需要检查UIKeyboardFrameEndUserInfoKey而不是UIKeyboardFrameBeginUserInfoKey。

做替换,你可能会解决它。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.