我有UITableView
这是我的视图控制器的属性。此视图控制器使用autolayout + storyboard约束定位在屏幕顶部下方40个像素处。我最近添加了一个标签和文本字段,它们最初隐藏在故事板中,并且被限制在桌面视图的后面。
我添加了一个显示这些字段的方法:
-(void)showNeighborhoodFilter {
[UIView animateWithDuration:.5 animations:^{
if (self.neighborhoodLabel.hidden) {
self.neighborhoodLabel.hidden=NO;
self.neighborhoodSelector.hidden=NO;
self.tableView.frame = CGRectMake(0, self.tableView.frame.origin.y+40, self.tableView.frame.size.width, self.tableView.frame.size.height-40);
}
else{
self.neighborhoodLabel.hidden=YES;
self.neighborhoodSelector.hidden=YES;
self.tableView.frame = CGRectMake(0, self.tableView.frame.origin.y-40, self.tableView.frame.size.width, self.tableView.frame.size.height+40);
}
}];
}
答案 0 :(得分:1)
要更改文本字段高度,请在控制器中声明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是tableview TPKeyboardAvoiding
的一部分,则可以使用某些第三方代码请参阅此链接:How to make a UITextField move up when keyboard is present?
答案 1 :(得分:0)
如果使用自动布局,则无法移动具有约束的视图,只要iOS决定重新计算约束,它就会再次移动。
您需要更改约束(您可以更改常量),或启用/禁用约束。