1

I’m trying to move the content up when the keyboard appears. This is the content which is a simple login form.

enter image description here enter image description here

Please note that these are not UITextFields. Its just a small UITableView in the middle of a UIViewController. And I have a UIScrollView filling the view controller embedding that table view.

I’ve registered for the keyboard notifications, UIKeyboardDidShowNotification and UIKeyboardWillHideNotification.

And in the method that fires when the keyboard appears, I've implemented a variation of this answer which does pretty much the same thing, setting the bottom value of the UIEdgeInsets which is used to set the contentInset of the scroll view.

func keyboardWasShown(notification: NSNotification) {

    var info: NSDictionary = notification.userInfo as NSDictionary
    var keyboardSize: CGSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size

    let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

The problem is it doesn't do anything. I successfully get the height of the keyboard but nothing changes. Can anybody tell me why and what I should do to fix this please?

Thank you.

4

3 回答 3

2

经过一番挣扎,我能够完成我想要的。我所做的是,在viewDidLoad我注册了键盘通知。当键盘出现时,我将它的框架放入一个变量中,并将登录表单(它是一个表格视图)的框架放入另一个变量中。

通过使用CGRectIntersection,当键盘与登录表单重叠并达到其高度时,我得到了相交部分的框架。然后我只需在滚动视图的setContentOffset方法中设置它以自动向上移动滚动视图。要将其移回原始位置,我只需将滚动视图的contentOffset属性再次设置为CGPointZero.

func registerForKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification) {
    var info: NSDictionary = notification.userInfo as NSDictionary
    var keyboardFrame: CGRect = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue()
    var loginFormFrame: CGRect = self.view.convertRect(self.tableView.frame, fromView: nil)
    var coveredFrame: CGRect = CGRectIntersection(loginFormFrame, keyboardFrame)

    self.scrollView.setContentOffset(CGPointMake(0, coveredFrame.height + 20), animated: true)
}

func keyboardWillBeHidden(notification: NSNotification) {
    self.scrollView.contentOffset = CGPointZero
}
于 2014-08-05T13:08:42.000 回答
2
UIEdgeInsets UIEdgeInsetsMake (
   CGFloat top,
   CGFloat left,
   CGFloat bottom,
   CGFloat right
);

你正在设置底部。尝试设置顶部插图。也许负值会有所帮助。

于 2014-08-05T09:35:18.010 回答
-1

ContentInset表示内容视图与封闭滚动视图的距离。您需要做的是更改 origin.y 值。

请参阅如何在键盘存在时使 UITextField 向上移动?

于 2014-08-05T09:36:23.260 回答