如何在运行时禁用ios中的约束?

时间:2015-07-08 11:48:41

标签: ios autolayout uikit nslayoutconstraint

我的视图中还有一些文本字段。我已经将视图的宽高比设置为self&它的超级视野。现在,当我单击文本字段然后出现键盘时,我正在调整视图的大小。设置其y位置,以便键盘不覆盖文本字段。我正在使用下面的代码。

$("td[title='" + title + "']").popover(options).popover('show');

现在当我的视图高度增加时,它的宽度也会增加,因为我已经设置了约束。请告诉我如何解决此问题。在这种情况下,我不想增加视图的宽度。

2 个答案:

答案 0 :(得分:3)

混合Autolayout约束和直接帧操作通常是一个坏主意,你可能应该避免这种情况。我建议您为要移动/调整大小的视图的高度或位置约束制作一些IBOutlet,并在委托回调中更改constraint.constant而不是更改帧。

此外,在处理键盘事件时,最好先听一下键盘通知(UIKeyboardWillShowNotification),而不是使用文本字段委托方法。

添加了一个gif来更好地说明 -

enter image description here

项目中的一些代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self addKeyboardNotificationsObserver];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)addKeyboardNotificationsObserver {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

- (void)handleKeyboardWillShow:(NSNotification *)paramNotification

{

    NSDictionary* info = [paramNotification userInfo];

    //when switching languages keyboard might change its height (emoji keyboard is higher than most keyboards).
    //You can get both sizes of the previous keyboard and the new one from info dictionary.

    // size of the keyb that is about to disappear
    __unused CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    // size of the keyb that is about to appear
    CGSize kbSizeNew = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    //make adjustments to constraints here...

    self.redSquareBottomConstraint.constant = kbSizeNew.height;

    //and this is where magic happens!

    [self.view layoutIfNeeded];

}

- (void)handleKeyboardWillHide:(NSNotification *)paramNotification

{
    //adjust constraints

    self.redSquareBottomConstraint.constant = 0;

    [self.view layoutIfNeeded];

}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

从代码中可以看出,我们从通知附带的userInfo字典中提取键盘的大小。正如 nhgrif 所指出的,您可以从中提取一些其他有价值的信息,例如动画的持续时间(键 - UIKeyboardAnimationDurationUserInfoKey)或曲线(键 - UIKeyboardAnimationCurveUserInfoKey)键盘出现/消极。文档here。如果你想要特定的动画行为,你可以在动画块中包装布局调用,如下所示:

[UIView animateWithDuration:duration
                 animations:^{

    [self.view layoutIfNeeded];

}];

答案 1 :(得分:-3)

只需为宽度约束制作IBOutlet,并在更改帧时重新分配#&高度!!