【发布时间】:2020-10-28 10:22:31
【问题描述】:
我创建了一个视图控制器,其 UIView 包含一个文本字段(注意:视图控制器显示为模式)。当您点击文本字段时,会出现一个键盘,并且 UIView 会在屏幕上向上移动,这样文本字段就不会被遮挡。但是,我的目标是从一开始就显示键盘和(不被遮挡的)UIView,当模式最初出现时,我正在努力实现。
我尝试将 textField.becomeFirstResponder() 插入 viewDidLoad,但这会显示键盘而不会将 UIView 移动到所需的(即可见的)位置。我也尝试将其插入 viewDidAppear,但这首先显示 UIView,然后停顿一秒钟,然后显示键盘并在非常尴尬的过渡中向上移动 UIView。
如果有人能提供一些建议来解决这个问题,那就太好了。我的代码如下。
@IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
//The line below will display the keyboard over the UIView, thus obscuring it.
textField.becomeFirstResponder()
}
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
self.view.frame.origin.y = 0 - keyboardSize!.height
}
以下是视觉参考。
【问题讨论】:
标签: ios swift uiview uitextfield uiresponder