UIScrollView的contentInset不起作用

时间:2014-08-05 09:25:42

标签: ios uitableview uiscrollview swift uiedgeinsets

我正试图在键盘出现时移动内容。这是一个简单登录表单的内容。

enter image description here enter image description here

请注意,这些不是UITextField。它只是UITableView中间的一个小UIViewController。我有一个UIScrollView填充嵌入该表视图的视图控制器。

我已注册键盘通知,UIKeyboardDidShowNotificationUIKeyboardWillHideNotification

在键盘出现时触发的方法中,我实现了this答案的变体,这几乎完全相同,设置了bottom的{​​{1}}值用于设置滚动视图的UIEdgeInsets

contentInset

问题是它什么都没做。我成功地获得了键盘的高度但没有任何变化。任何人都可以告诉我为什么以及我应该做些什么来解决这个问题?

谢谢。

3 个答案:

答案 0 :(得分:2)

UIEdgeInsets UIEdgeInsetsMake (
   CGFloat top,
   CGFloat left,
   CGFloat bottom,
   CGFloat right
);

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

答案 1 :(得分: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
}

答案 2 :(得分:-1)

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

请参阅How to make a UITextField move up when keyboard is present?

相关问题