ios – 如何在使用“自动布局”弹出键盘时调整视图大小

我有一个视图(在这种情况下是UITableView,但这并不重要)在我的UIViewController上,我希望在键盘弹出时调整高度.

自动布局中执行此操作的最佳方法是什么?目前在视图中我有这些约束:@H_502_3@

>超级视图的顶级空间:0
>超级视图的尾随空格:0
>超级视野的领先空间:0
>底层空间到superview:0
>身高等于= 424@H_502_3@

我认为最快的方法删除高度和底部空间约束,并在调用keyboardDidAppear通知时调整代码中的实际视图,但还有其他方法吗?@H_502_3@

编辑:我删除了高度限制,我的坏.@H_502_3@

解决方法

我会给你一个通用的想法,它可能需要根据你的实际项目进行重新调整.

swift 4.x@H_502_3@

let notificationTokenKeyboardWillAppear = NotificationCenter.default.addobserver(forName: NSNotification.Name.UIKeyboardWillShow,object: nil,queue: nil) { (note) in
    guard let keyboardFrame = (note.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
    UIView.animate(withDuration: CATransaction.animationDuration(),animations: {
        tableView.contentInset = UIEdgeInsets(top: 0.0,left: 0.0,bottom: keyboardFrame.size.height,right: 0.0)
    },completion: nil)
}

和@H_502_3@

let notificationTokenKeyboardWillHide = NotificationCenter.default.addobserver(forName: NSNotification.Name.UIKeyboardWillHide,queue: nil) { (_) in
    UIView.animate(withDuration: CATransaction.animationDuration(),animations: {
        tableView.contentInset = .zero
    },completion: nil)
}

注意:当您要释放视图并且不再需要基于闭包的观察者时,您需要通过调用removeObserver(_:)方法手动删除令牌@H_502_3@

ObjC@H_502_3@

我认为UITableView * _tableView已经在以前的某个地方正确设置了.@H_502_3@

- (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];
     }];


     // ...

}@H_502_3@

注意:如果您的UITableView不在屏幕的底部,则应在此行中细化contentInset值:[_ tableView setContentInset:UIEdgeInsetsMake(0.f,_ keyboardFrame.size.height,0.f)] ;@H_502_3@

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...