【问题标题】:Transition UIButton image from one image to another将 UIButton 图像从一个图像转换到另一个图像
【发布时间】:2016-07-14 06:08:35
【问题描述】:

我是 iOS 开发的新手,我选择使用 Swift 作为我的语言。我正在为我儿子开发一个简单的小程序,它在 UIButtons 上显示动物的图像,当他选择正确的按钮时,所有按钮都会加载新图像,并要求他找到不同的动物。

该程序的基本功能已启动并正在运行,他可以玩它,但现在我想继续让它变得更漂亮。选择正确的图像时,是时候使用新的替换按钮映像,我使用新的映像:

btnItem.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal)

我想通过动画过渡来进行更改,而不是简单地将按钮的图像从一个更改为另一个,但我不知道如何。

我发现 UIViews 上的过渡与永久动画按钮图像有很多关系,但对于诸如溶解或从左向右滑动等过渡没有任何意义。

This question 上的 SO 与我的几乎相同,但答案使用的是 Objective-C。

那么,长话短说,有没有办法在 Swift 中将 UIButton 图像从一个转换到另一个?

提前感谢您的宝贵时间。

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    使用 Swift 4.0

    在下方更新
     UIView.transition(with: sender as! UIView, duration: 1.5, options: .transitionFlipFromRight, animations: {
                sender.setImage(UIImage(named: arrItems[intItemCounter]), for: .normal)
            }, completion: nil)
    

    UIButton 是 UIView 的子类,因此您可以将 UIView.animateWithDuration 与按钮一起使用。例如,您可以这样说:

    @IBAction func buttonPressed(sender: UIButton) {
            UIView.transitionWithView(sender, duration: 1.5, options: .TransitionFlipFromRight, animations: {
                    sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal)
                }, completion: nil)
    
        }
    

    这将导致在点击时按钮与新图像一起翻转。

    如果您想要其他示例中的动画(淡出/淡入),您可以说:

    @IBAction func buttonPressed(sender: UIButton) {
                UIView.animateWithDuration(0.5, animations: {
                        sender.alpha = 0.0
                    }, completion:{(finished) in
                        sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal)
                        UIView.animateWithDuration(0.5,animations:{
                        sender.alpha = 1.0
                        },completion:nil)
                 })
    
            }
    

    您也可以像这样进行交叉溶解:

    @IBAction func buttonPressed(sender: UIButton) {
            UIView.transitionWithView(sender, duration: 1.5, options: .TransitionCrossDissolve, animations: {
                sender.setImage(UIImage(named: arrItems[intItemCounter]), forState: .Normal)
                }, completion: nil)
    
        }
    

    【讨论】:

    • 感谢您的快速回复。经过测试和工作。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多