【发布时间】:2018-12-26 23:53:18
【问题描述】:
我有以下问题:我有一个scrollView,里面有一个textField。我需要当我点击textField 时,键盘会出现,textField(在滚动条内)会立即(同时)向上移动键盘显示。现在textField 出现但有延迟,比如键盘显示后几毫秒,如下所示:
更新:
我已经重写了这样的键盘处理方法:
override func keyboardWillShow(_ notification: Notification!) {
guard let userInfo = notification.userInfo, let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
// this constraint -> viewContainerButtonBottomConstraint
//refers to the button that must have above the keyboard
//when keyboard shows up.
self.viewContainerButtonBottomConstraint.constant = frame.height
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: frame.height, right: 0)
scrollView.contentInset = contentInset
if #available(iOS 11.0, *) {
self.viewContainerButtonBottomConstraint.constant -= self.view.safeAreaInsets.bottom
}
}
override func keyboardWillHide(_ notification: Notification!) {
scrollView.contentInset = UIEdgeInsets.zero
self.viewContainerButtonBottomConstraint.constant = 0
UIView.animate(withDuration: 1, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
观察者的注册是在父类中进行的:
- (void)addNotificationKeyboard {
if (kKeyboardNotificationsShowAvailable) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShowNotification:)
name:UIKeyboardWillShowNotification
object:nil];
}
if (kKeyboardNotificationsHideAvailable) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHideNotification:)
name:UIKeyboardWillHideNotification
object:nil];
}
}
并且方法keyboardWillShowNotification 和keyboardWillHideNotification 也在父类中,它们像我上面展示的那样被覆盖:
- (void)keyboardWillShowNotification:(NSNotification*)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo
valueForKey:UIKeyboardFrameEndUserInfoKey];
self.keyboardHeight = [keyboardFrameBegin CGRectValue].size.height;
}
- (void)keyboardWillHideNotification:(NSNotification*)notification
{
if (self.view.frame.origin.y != 0) {
if (self.tabBarController) {
if (!(self.view.frame.origin.y == 64))
[UIUtilities moveView:self.view newYposition:-64];
}
else
[UIUtilities moveView:self.view newYposition:0];
}
[self.view endEditing:YES];
}
提前感谢您的回答!
【问题讨论】:
-
内嵌图片而不是链接。
-
这似乎是大多数 Apple 应用程序的默认行为,似乎是故意的。您可以计算所需的偏移量并将其设置为滚动或表格视图的
contentInset.bottom属性,但我强烈建议您保留操作系统实现。 -
我认为您可能使用的是
keyBoardDidShow而不是keyboardWillShow通知。 -
@RakeshaShastri 我正在使用keyboardWillShow.. :(,虽然我尝试覆盖这两种方法但仍然相同
-
请显示您的通知注册码和选择器方法。
标签: ios swift uiscrollview keyboard uitextfield