我可以给你一个通用的想法,但可能需要根据你实际的项目进行重新调整。
Swift 4.2
let notificationTokenKeyboardWillAppear = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (note) in
guard let keyboardFrame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
UIView.animate(withDuration: CATransaction.animationDuration(), animations: {
self.scrollView?.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardFrame.size.height, right: 0.0)
}, completion: nil)
}
和
let notificationTokenKeyboardWillHide = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (_) in
UIView.animate(withDuration: CATransaction.animationDuration(), animations: {
self.scrollView?.contentInset = .zero
}, completion: nil)
}
注意1:scrollView
在此表示任何 UIScrollView
的子集,例如UITableView
或 UICollectionView
等。
注意2:当您要释放视图且基于闭包的观察者不再需要时,您需要通过调用 removeObserver(_:)
方法手动删除令牌。
ObjC
我假设 UITableView *_tableView
已经在其他地方正确设置好了。
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
id _obj = [note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect _keyboardFrame = CGRectNull;
if ([_obj respondsToSelector:@selector(getValue:)]) [_obj getValue:&_keyboardFrame];
[UIView animateWithDuration:0.25f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
[_tableView setContentInset:UIEdgeInsetsMake(0.f, 0.f, _keyboardFrame.size.height, 0.f)];
} completion:nil];
}];
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
[UIView animateWithDuration:0.25f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
[_tableView setContentInset:UIEdgeInsetsZero];
} completion:nil];
}];
}
注意: 如果你的 UITableView
不是精确地位于屏幕底部,则应该在此行中调整 contentInset
的值: [_tableView setContentInset:UIEdgeInsetsMake(0.f, 0.f, _keyboardFrame.size.height, 0.f)];