将UIView底部空间约束设置为键盘高度

时间:2015-08-05 16:44:40

标签: xcode autolayout

我是autolayout的忠实粉丝,但总是在Storyboard中实现它。

我有一个UIView,我希望底部空间约束是键盘结束的地方。

我已经定义了所有约束,有人可以告诉我如何在代码中仅为底部空间实现此约束吗?以及如何根据特定的iDevice获取键盘高度的值,并将其与约束匹配。

由于

1 个答案:

答案 0 :(得分:2)

像这样

取出视图底部约束的出口
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintContainerBottom;

并使用此

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupKeyboard:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self setupKeyboard:NO];
}

- (void)setupKeyboard:(BOOL)appearing
{
    if (appearing) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    }
}

- (void)keyboardWillShow:(NSNotification*)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView beginAnimations:@"keyboardShown" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];

    self.constraintContainerBottom.constant = keyboardSize.height;
    [self.view layoutIfNeeded];

    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView beginAnimations:@"keyboardHidden" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];

    self.constraintContainerBottom.constant = 0;
    [self.view layoutIfNeeded];

    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}