Ios 显示键盘时管理UIScrollView内容
在教程中,当键盘出现时移动文本字段所需的代码就在这里。但是,代码不会检查键盘上的字符是否与文本字段重叠。奇怪的是,即使没有代码检查键盘和文本字段的重叠,它也能工作。当键盘与文本字段重叠时,滚动视图向上移动;当键盘与文本字段不重叠时,滚动视图不移动Ios 显示键盘时管理UIScrollView内容,ios,swift,uiscrollview,keyboard,Ios,Swift,Uiscrollview,Keyboard,在教程中,当键盘出现时移动文本字段所需的代码就在这里。但是,代码不会检查键盘上的字符是否与文本字段重叠。奇怪的是,即使没有代码检查键盘和文本字段的重叠,它也能工作。当键盘与文本字段重叠时,滚动视图向上移动;当键盘与文本字段不重叠时,滚动视图不移动 NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification
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];
}
请解释为什么示例代码不需要进行检查?您可能需要检查此库我不擅长swift,但它看起来好像添加了一些delta hightOfKeybord,然后滚动到它。无论如何,为什么不尝试在Xcode中调试视图呢。