为了改变文本文件的高度,在你的控制器中声明 NSLayoutConstraint 变量约束。
在 .h 文件中:
__weak IBOutlet NSLayoutConstraint *heightConstraintOfMyView;//height of the view
__weak IBOutlet NSLayoutConstraint *verticalspaceConstraintOfMyViewWithTopView;//space between myview and the view just above it
__weak IBOutlet NSLayoutConstraint *verticalSpaceConstraintOfMyViewWithBottomView;//space between myview and the view just below it
在您的故事板中
已连接
使用约束改变框架。
if (myConditionTrueForShowingView) {
//setting the constraint to update height
heightConstraintOfMyView = 40;
verticalspaceConstraintOfMyViewWithTopView.constant=20;
verticalSpaceConstraintOfMyViewWithBottomView.constant=80;
}
else{
//setting the constraint to update height
heightConstraintOfMyView = 0;
verticalspaceConstraintOfMyViewWithTopView.constant=20;
verticalSpaceConstraintOfMyViewWithBottomView.constant=0;
}
您还可以注册键盘通知。
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
并在通知回调中处理高度变化-
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableBottomSpaceConstrain;
-(void)keyboardWasShown:(NSNotification*)aNotification
{
self.view.translatesAutoresizingMaskIntoConstraints = YES;
if (self.tableBottomSpaceConstrain.constant) {//
return;
}
self.tableBottomSpaceConstrain.constant = 216;// Default Keyboard height is 216, varies for third party keyboard
[self.view setNeedsUpdateConstraints];
[self.view updateConstraints];
[self.view layoutIfNeeded];
[self.view setNeedsLayout];
[self.view setNeedsUpdateConstraints];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
self.tableBottomSpaceConstrain.constant =0;
[self.view layoutIfNeeded];
[self.view setNeedsLayout];
[self.view updateConstraints];
}
了解更多关于 NSLayoutConstraint
Implementing AutoLayout Constraints in Code
见Apple Doc
如果 textfield 是 tableviewTPKeyboardAvoiding 的一部分,您可以使用一些第三方代码
查看此链接:How to make a UITextField move up when keyboard is present?
Making a UITableView scroll when text field is selected