ios - 将 UIButton 图像从一个图像过渡到另一个图像

标签 ios swift uibutton

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

程序的基础知识已经启动并运行,他可以玩,但现在我想继续让它变得更漂亮。 When the correct image is selected and it's time to replace the button images with new ones I use:

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

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

我发现很多与 UIView 上的过渡有关,也与永久动画按钮图像有关,但与过渡无关,例如溶解或从左向右滑动或其他任何东西。

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

所以,长话短说,有没有一种方法可以在 Swift 中将 UIButton 图像从一个图像转换到另一个图像?

提前感谢您抽出时间。

最佳答案

下面用 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)

    }

关于ios - 将 UIButton 图像从一个图像过渡到另一个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36237668/

相关文章:

ios - 带有属性文本的 UIButton 不遵守 adjustsFontSizeToFitWidth

javascript - 滚动顶部动画在 IOS 上不工作

ios - 在 120 个字符后附加 readmore 标签,并使其在 ios 中可点击

ios - 如何在 iOS 上绘制成 PDF?

swift - 在 SWIFT 中的 xib 文件上呈现 ViewController

ios - 如何将 .txt 文件的一部分加载到 TextView 上以消除延迟现象

ios - UIButton:设置 ImageView 的背景(不设置图像)

swift - 根据 titleLabel 的长度调整 UIButton 的大小

ios - 从单个单位数组构建 NSCalendarUnit 值

ios - 我无法在注册表单中添加性别的 UIPickerview