显示或隐藏键盘时调整UIView [英] Adjusting a UIView when the keyboard shows or hides

查看:75
本文介绍了显示或隐藏键盘时调整UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am adding a keyboard observer to adjust the view height when the keyboard shows. But when the text field is at the top of the view and the keyboard shows, the text field goes up even more. Can someone please guide me on how to fix this properly because after performing lots of searches, they all suggest the same thing. I am using iOS 9 on an iPhone 5.

这是我的代码.在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
        })
    }
}

推荐答案

您正在采用复杂的方法来解决不是很困难的问题.请记住,手机的尺寸多种多样,因此尝试移动视图对于一台设备(例如iPhone 5)可能效果很好,但在其他设备(例如iPhone 4,iPhone 6s)上体验不佳.

You're taking a complicated approach to what isn't a very difficult problem. Please remember that phones come in a variety of sizes, so trying to move a view around might work great for one device (e.g. iPhone 5) but be a poor experience on others (e.g. iPhone 4, iPhone 6s).

您正在寻找的解决方案是将控件放在UIScrollView中.然后,当键盘显示或隐藏时,您就不会移动任何内容-您只需调整滚动视图的内容插图,然后让iOS进行其余操作即可.

The solution you're looking for is to place your controls inside a UIScrollView. You then don't move anything when the keyboard shows or hides – you just adjust the content inset of your scroll view, and let iOS do the rest.

由于有些硬件键盘可以随意连接和拔出,因此显示和隐藏的键盘变得很复杂.在(极其广泛的!)测试中,无论键盘发生什么情况,我都设法将似乎在所有情况下均能正常运行的代码组合在一起.我尝试将其缩小,并总是发现它无法正常工作的边缘情况,因此我采用了这种固定方法,效果很好.如果您可以使用UIScrollView,则此精确方法也将为您工作.

The keyboard being shown and hidden is complicated by the fact that there are also hardware keyboards that can be connected and unplugged at will; in my (extremely extensive!) testing, I've managed to pull together code that seems to behave properly in all conditions, no matter what happens with the keyboard. I've tried to trim it down smaller and have always found an edge case where it stopped working, so I've settled with this fixed approach and it works great. If you're able to use a UIScrollView, this exact approach will work for you too.

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

Step 1: Register for the right notifications. Specifically, put this into viewDidLoad():

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

步骤2:将此方法添加到您的视图控制器中:

Step 2: Add this method to your 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的任何人也应在该方法的末尾添加这两行,以使用户不会失去位置:

Step 3: Anyone using a UITextView should also add these two lines to the end of that method so the user doesn't lose their place:

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

…尽管在这种情况下大概是yourTextView或类似的

…although presumably in that case it would be yourTextView or similar.

这篇关于显示或隐藏键盘时调整UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆