从下往上动画 UIButton 背景颜色,Objective C

Animate UIButton Background color from bottom up, Objective C

我有一个按钮,我想为背景颜色设置动画,就好像它从底部到顶部填充一样。

现在我只是用动画改变颜色

[UIView animateWithDuration:2.0 animations:^{
    button.layer.backgroundColor = [UIColor redColor].CGColor;
} completion:NULL];

效果很好,但我希望动画从下往上填充,就像充满液体一样。

编辑:不确定是否有所不同,但按钮是圆形的

如果您只需要从下到上填充背景颜色,您可以使用该颜色和原点 Y = CGRectGetHeight(button.frame) 创建附加层。当您需要填充按钮时,只需将该层的原点 Y 设置为 0。

试试这个。这里 btn 是您按钮的出口,v 是我们将添加到您的按钮以实现动画目的的视图。

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, [self btn].frame.size.height,
                                                     [self btn].frame.size.width, [self btn].frame.size.height)];
[v setBackgroundColor:[UIColor purpleColor]];
v.userInteractionEnabled = NO;
v.exclusiveTouch = NO;
[[self btn] addSubview:v];

[UIView animateWithDuration:0.45 animations:^{

    CGRect currentRect = v.frame;
    currentRect.origin.y = 0;
    [v setAlpha:1];
    [v setFrame:currentRect];
    [[self btn] sendSubviewToBack:v];
}];

Swift 版本的 答案。

let v = UIView(frame: CGRect(x: 0, y: self.btn.frame.size.height, 
                                   width: self.btn.frame.size.width,
                                   height: self.btn.frame.size.height))
v.backgroundColor = .purple
v.isUserInteractionEnabled = false
v.isExclusiveTouch = false
self.btn.addSubview(v)

UIView.animate(withDuration: 0.45) {
    var currentRect = v.frame
    currentRect.origin.y = 0
    v.alpha = 1.0
    v.frame = currentRect
    self.btn.sendSubview(toBack: v)
}