动画添加高度限制到键盘扩展视图

时间:2018-09-29 20:31:30

标签: ios autolayout ios-autolayout ios-keyboard-extension

在我的键盘扩展中,有一个特定的viewController,我想使键盘的高度增加。在呈现此viewController之前,主UIInputViewController会自行调用此方法,并传递400.0的值:

- (void)setKeyboardHeight:(CGFloat)height {
    if (self.heightConstraint) {
        [self.view removeConstraint:self.heightConstraint];
        self.heightConstraint = nil;
   }

    self.heightConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:height];

    [self.view addConstraint:self.heightConstraint];

    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}

键盘的高度确实更改为指定的值,但未设置动画。这是不可能完成的,还是我只是在键盘扩展中使用了错误的方法?

1 个答案:

答案 0 :(得分:0)

这是我想出的一个解决方案。调用animateKeyboardHeightTo: speed:并将您希望键盘更改为targetHeight的高度并将每毫秒的点数更改为speed,键盘将增加或减少到指定的高度。我尝试使用持续时间而不是速度,每次迭代增加一点,并计算dispatch_after的持续时间,以便整个动画将在指定的持续时间内发生,但我无法执行dispatch_after足够快。我不知道它是否仅仅是不够精确,还是不能以不到1秒的间隔执行,但这是我唯一能想到的解决方案。

如果要在大小之间切换,可以在对self.view.frame.size.height进行首次调用之前将animateKeyboardHeightTo: speed:存储在属性中,然后再次调用此方法并传递存储的高度以恢复键盘达到其初始高度。

- (void)animateKeyboardHeightTo:(CGFloat)targetHeight speed:(CGFloat)speed {
    CGFloat initialHeight = self.view.frame.size.height;

    if (targetHeight < initialHeight) {
        speed = -speed;
    }
    [self setKeyboardHeight:initialHeight];
    [self increaseKeyboardHeightToTargetHeight:targetHeight speed:speed];
}

- (void)increaseKeyboardHeightToTargetHeight:(CGFloat)targetHeight speed:(CGFloat)speed {
    CGFloat currentHeight = self.heightConstraint.constant;
    CGFloat nextHeight = currentHeight + speed;
    if ((speed > 0 && nextHeight > targetHeight) || (speed < 0 && nextHeight < targetHeight)) {
        nextHeight = targetHeight;
    }
    [self setKeyboardHeight:nextHeight];

    if ((speed > 0 && nextHeight < targetHeight) || (speed < 0 && nextHeight > targetHeight)) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            [self increaseKeyboardHeightToTargetHeight:targetHeight speed:speed];
        });
    }
}

- (void)setKeyboardHeight:(CGFloat)height {
    [self removeHeightConstraint];
    [self addHeightConstraintWithHeight:height];
}

- (void)removeHeightConstraint {
    if (self.heightConstraint) {
        [self.view removeConstraint:self.heightConstraint];
        self.heightConstraint = nil;
    }
}

- (void)addHeightConstraintWithHeight:(CGFloat)height {
    self.heightConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:height];

    [self.view addConstraint:self.heightConstraint];
}