键盘出现时管理UIScrollView内容

时间:2015-02-09 15:45:13

标签: ios swift uiscrollview keyboard

在教程中,键盘出现时移动textField所需的代码就在这里。但是,代码不会检查键盘是否与textField重叠。奇怪的是,即使没有代码来检查键盘和textField的重叠,它仍然有效。当键盘与textField重叠时,scrollView会向上移动,当键盘与textField不重叠时,scrollView不会移动。

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
  }

  deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}

  func keyboardWillShow(notification: NSNotification) {
adjustInsetForKeyboardShow(true, notification: notification)
   }

func keyboardWillHide(notification: NSNotification) {
adjustInsetForKeyboardShow(false, notification: notification)
}

  func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keyboardFrame) - CGRectGetHeight(navigationController!.toolbar.frame) + 20) * (show ? 1 : -1)

fgScrollView.contentInset.bottom += adjustmentHeight
fgScrollView.scrollIndicatorInsets.bottom += adjustmentHeight

println("\(fgScrollView.contentInset.bottom)")
  }

在对苹果开发者网站进行一些研究之后,我发现苹果确实使用了一些代码来检查是否确实发生了重叠。 代码如下所示

// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
    [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}

请解释为什么示例代码不需要进行检查?

0 个答案:

没有答案