我的 UIViewController
上有一个 View (在本例中为 UITableView
,但这并不重要),我希望在弹出键盘时调整高度。
在自动布局中执行此操作的最佳方法是什么?目前在 View 中我有这些限制:
- super View 的顶部空间:0
- 父 View 的尾随空间:0
- super View 的前导空间:0
- 父 View 的底部空间:0
高度= 424
我认为最快的方法是删除高度和底部空间限制,并在调用 keyboardDidAppear
通知时调整代码中实际 View 的大小,但是还有其他方法可以做这个?
编辑:我删除了高度限制,我的错。
最佳答案
我会给你一个通用的想法,它可能需要根据你的实际项目重新调整。
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(_:)
手动删除 token 当您即将释放 View 并且不再需要基于闭包的观察者时的方法
对象
我认为 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)];
关于ios - 使用自动布局弹出键盘时如何调整 View 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23988866/