【问题标题】:How to correctly determine keyboard and text field position on iOS?如何正确确定 iOS 上的键盘和文本字段位置?
【发布时间】:2019-01-08 20:48:34
【问题描述】:

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

@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 下方。我该如何解决这个问题?

【问题讨论】:

  • 你用过UIScrollView吗?
  • 不,这不是 ScrollView

标签: ios swift cocoa-touch autolayout


【解决方案1】:

如果对约束进行了任何更改,则需要调用 self.view.layoutIfNeeded()。 你可以在动画块中调用它

UIView.animate(withDuration: 持续时间, 延迟:时间间隔(0), 选项:动画曲线, 动画:{ self.view.layoutIfNeeded() }, 完成:无)

【讨论】:

  • 如果我添加这个,什么都不会发生。
【解决方案2】:

步骤:- 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)
}

【讨论】:

猜你喜欢
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2014-10-31
相关资源
最近更新 更多