首页 > 解决方案 > 如何正确确定 iOS 上的键盘和文本字段位置?

问题描述

当键盘显示并且文本字段变得不可见时,我想提升视图。这是我的代码:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let tfPos = lastTextField!.convert(lastTextField!.frame, to: self.view)
        let tfBottom = tfPos.origin.y
        let kbTop = keyboardSize.origin.y

        if kbTop < tfBottom {
            self.verticalCenterConstraint.constant = -(tfBottom - kbTop)
        }
    }
}

我确定键盘的顶部,然后是文本字段的底部。但是,文本字段的位置不正确,即使我可以在屏幕上清楚地看到它在键盘上方,但我的代码说它在 35pt 下方。我该如何解决?

标签: iosswiftcocoa-touchautolayout

解决方案


步骤 :- 1 为隐藏和显示通知添加观察者

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), 
name: Notification.Name.UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), 
name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)

步骤:- 2 实施目标方法

@objc func adjustForKeyboard(notification: Notification) {
let userInfo = notification.userInfo!

let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)

if notification.name == Notification.Name.UIKeyboardWillHide {
    yourTextView.contentInset = UIEdgeInsets.zero
} else {
    yourTextView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}

yourTextView.scrollIndicatorInsets = yourTextView.contentInset

let selectedRange = yourTextView.selectedRange
yourTextView.scrollRangeToVisible(selectedRange)
}

推荐阅读