【问题标题】:Animate a UIButton为 UIButton 设置动画
【发布时间】:2011-10-31 00:13:32
【问题描述】:

我想知道是否有可能有一个 UIButton 在未触动时会产生动画?

不确定这是否完全合理。我有一个 UIButton,我通过 IB 在我的 XIB 上放置了它。我使用自定义类型和我自己的 75x75 图像作为控制状态默认值。当用户触摸按钮时,我没有设置自定义图像,所以它只会变暗,这很好。

但是,当按钮未被触摸时,我希望它在两个或三个不同的自定义图像之间进行动画处理,以使其具有围绕外边缘“发光”的效果。这可以吗?

【问题讨论】:

    标签: iphone objective-c ios4 uibutton


    【解决方案1】:

    您可能需要深入到核心动画层。 UIButton 图层的阴影属性是可动画的,因此您可以创建重复的 CABasicAnimation 我更改阴影颜色/大小并将其添加到图层。以下代码对我有用。

    button.layer.shadowPath = [[UIBezierPath bezierPathWithRect:CGRectInset(button.bounds, -3, -3)] CGPath];
    button.layer.shadowColor = [[UIColor whiteColor] CGColor];
    button.layer.shadowOpacity = 1.0f;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowColor"];
    animation.fromValue = (id)[[UIColor darkGrayColor] CGColor];
    animation.toValue = (id)[[UIColor lightGrayColor] CGColor];
    animation.duration = 1.0f;
    animation.autoreverses = YES;
    animation.repeatCount = NSIntegerMax;
    
    [button.layer addAnimation:animation forKey:@"shadow"];
    

    并将这些方法附加到按钮的控件事件中。

    -(IBAction)userDidTouchDown:(UIButton *)sender
    {
        [button.layer removeAnimationForKey:@"shadow"];
    }
    
    -(IBAction)userDidTouchUp:(UIButton *)sender
    {
    
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowColor"];
        animation.fromValue = (id)[[UIColor darkGrayColor] CGColor];
        animation.toValue = (id)[[UIColor lightGrayColor] CGColor];
        animation.duration = 1.0f;
        animation.autoreverses = YES;
        animation.repeatCount = NSIntegerMax;
    
        [button.layer addAnimation:animation forKey:@"shadow"];
    }
    

    您可以使用阴影值(尤其是路径)来获得适合您的效果。不要忘记附加 userDidTouchUp: 与内部修饰和外部修饰事件。

    【讨论】:

      【解决方案2】:

      你需要有一个自定义视图,因为 UIButton 不能做动画。 带有两个子视图的整个框架的 UIView: 底部是按钮,顶部是uiimageview。

      您将uiimageview 的animationImages 属性设置为您的帧。 根据需要隐藏/显示 uiimageview。

      【讨论】:

        猜你喜欢
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多