Animate UIButton Background color from bottom up,

2019-07-10 18:55发布

I have a button which I would like to animate the background color as if it is filling from the bottom to the top.

Right now I'm just changing the color with animation

i.e

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

This works just fine but I'd love the animation to fill from the bottom up like it is filling up with liquid.

EDIT: not sure if it makes a difference but the button is round

3条回答
贪生不怕死
2楼-- · 2019-07-10 19:17

If you need just background color filling from bottom to top, you could create additional layer with that color and origin Y = CGRectGetHeight(button.frame). When you need to fill your button just animate origin Y of that layer to 0.

查看更多
Bombasti
3楼-- · 2019-07-10 19:21

Swift version of Avi answer.

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)
}
查看更多
欢心
4楼-- · 2019-07-10 19:30

Try this. Here btn is the outlet to your button and v is the view we will be adding to your button for animation purpose.

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];
}];
查看更多
登录 后发表回答