ios - 在键盘显示或隐藏时调整 UIView

标签 ios swift2 uikeyboard

我正在添加一个键盘观察器来调整键盘显示时的 View 高度。但是当文本字段位于 View 的顶部并且键盘显示时,文本字段会上升得更多。有人可以指导我如何正确解决此问题,因为在执行大量搜索后,他们都提出了同样的建议。我在 iPhone 5 上使用 iOS 9。

这是我的代码。在 viewDidLoad() 中:

//SET OBSERVER WHEN KEYBOARD IS SHOWN
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: self.view.window)

//SET OBSERVER WHEN KEYBOARD IS HIDDEN
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: self.view.window)

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: self.view.window)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window)
}

//HANDLING KEYBOARD APPEARING AND DISAPPEARING
func keyboardWillHide(sender: NSNotification) {
    let userInfo: [NSObject : AnyObject] = sender.userInfo!
    let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
    self.view.frame.origin.y += keyboardSize.height
}

func keyboardWillShow(sender: NSNotification) {
    let userInfo: [NSObject : AnyObject] = sender.userInfo!
    let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
    let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size

    print(("\(keyboardSize.height)---\(offset.height)"))  **//this is always showing the values 216.0 for both** 

    if keyboardSize.height == offset.height {
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.frame.origin.y -= keyboardSize.height
        })
    } else {
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.frame.origin.y += keyboardSize.height - offset.height
        })
    }
}

最佳答案

您采用复杂的方法来解决不是很困难的问题。请记住,手机有多种尺寸,因此尝试移动 View 可能对一种设备(例如 iPhone 5)很有效,但对其他设备(例如 iPhone 4、iPhone 6s)来说体验很差。

您正在寻找的解决方案是将您的控件放在 UIScrollView 中。然后,当键盘显示或隐藏时,您不要移动任何东西 - 您只需调整 ScrollView 的内容插入,剩下的交给 iOS。

显示和隐藏的键盘比较复杂,因为还有可以随意连接和拔出的硬件键盘;在我的(极其广泛的!)测试中,我设法将似乎在所有条件下都能正常运行的代码组合在一起,无论键盘发生什么情况。我试图将它修剪得更小,并且总是发现它停止工作的边缘情况,所以我已经决定采用这种固定方法并且效果很好。如果您能够使用 UIScrollView,那么这种方法也适用于您。

第 1 步:注册接收正确的通知。具体来说,将其放入 viewDidLoad():

let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "adjustForKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: "adjustForKeyboard:", name: UIKeyboardWillChangeFrameNotification, object: nil)

第 2 步:将此方法添加到您的 View Controller :

func adjustForKeyboard(notification: NSNotification) {
    let userInfo = notification.userInfo!

    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)

    if notification.name == UIKeyboardWillHideNotification {
        yourScrollView.contentInset = UIEdgeInsetsZero
    } else {
        yourScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
    }

    yourScrollView.scrollIndicatorInsets = yourScrollView.contentInset
}

第 3 步:任何使用 UITextView 的人都应该将这两行添加到该方法的末尾,这样用户就不会丢失他们的位置:

let selectedRange = yourScrollView.selectedRange
yourScrollView.scrollRangeToVisible(selectedRange)

…虽然在那种情况下可能是 yourTextView 或类似的。

关于ios - 在键盘显示或隐藏时调整 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34314106/

相关文章:

swift - 存在键盘时向上移动 UITextField

ios - ReactiveCocoa 中的内存管理

swift - 获取不同表示形式的字符串长度的运行时复杂性

带有结构/协议(protocol)的 Swift 多态闭包分派(dispatch)

swift - <未知> :0: error: type 'Key' constrained to non-protocol type 'String'

ios - 在点击任何 UIControl 对象时关闭键盘

ios - 捕获其父 View 框架外的 subview 上的触摸(在多个层上)

ios - 是否可以在 xcode 中进入 ios 框架代码?

ios - 如何将 View Controller 添加到 ScrollView ,但仅在 ScrollView 显示该 vc 时实例化 View Controller ?

iphone - 如何创建一个行为类似于 UIKeyboard (Numberpad) 的 UIButton 矩阵?