ios - 在 Swift 中使用 UIButton 动画

标签 ios swift animation uibutton

我一直在尝试让这段代码正常工作,但我似乎无法让我的 UIButton 通过图像进行动画处理。

@IBOutlet weak var screenButton: UIButton!;

func animation(){
        var animationButton : UIButton!; 
        var imageList = [UIImage]();
        var image1:UIImage = UIImage(named:"3fingers-o-l-animation1.png")!;
        var image2:UIImage = UIImage(named:"4fingers-o-l-animation1.png")!;

        animationButtonscreenButton = screenButton;
        imageList = [image1, image2];

        animationButton!.imageView!.animationImages = imageList;
        animationButton!.imageView!.animationDuration = 1.0;
        animationButton!.imageView!.startAnimating();
    }

写完这段代码后,我从 screenButton 拖了一条线到我想通过 Storyboard 中的图像制作动画的按钮。 我究竟做错了什么?

最佳答案

你需要做的是不要在函数animation中重新初始化UIButton;所以,注释掉这一行:

//var animationButton : UIButton!

除了有一个IBOutlet,我们还需要一个IBAction 到你的函数animation。通过控制将“线”拖到功能 block (检查 IBAction,而不是 IBOutlet)来执行与按钮相同的操作。

当您仍在 Storyboard中时,进行一些演练:


  • 您只有一个名为:animationButton 的按钮,它是一个IBOutlet,通过按住控制键拖动“线”从您的 Storyboard到您的代码。

  • 对于您的动画 功能: 也从 Storyboard中按住 Control 键将“线”从按钮拖到 animation 函数的 block 。

  • 在 Storyboard中为您的按钮设置初始图像,如下所述。

此外,我们还需要在 Storyboard中设置一个初始图像;否则,按钮的图像属性为 nil

请在 Storyboard中单击右侧的“属性检查器”,然后在显示“图像”的位置设置图像。作为测试,我将其设置为“1.jpg”。

因此,您的代码应如下所示:

@IBOutlet weak var animationButton: UIButton!
@IBAction func animation()
{
    print("button touched")
    //var animationButton : UIButton!
    var imageList = [UIImage]()
    var image1:UIImage = UIImage(named:"1.jpg")!
    var image2:UIImage = UIImage(named:"2.jpg")!

    //animationButtonscreenButton = screenButton;
    imageList = [image1, image2];

    animationButton!.imageView!.animationImages = imageList
    animationButton!.imageView!.animationDuration = 1.0
    animationButton!.imageView!.startAnimating()
}

刚刚进行了快速测试;它获得触摸事件并且图像在按钮上动画。希望这会有所帮助。

关于ios - 在 Swift 中使用 UIButton 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32080231/

相关文章:

ios - 表达式类型 '@lvalue String?' 在没有更多上下文的情况下不明确

ios - 查看使用 Lightning 端口连接到 iPhone 的设备的电池百分比

actionscript-3 - 为什么此 ActionScript Flip 会导致我的网站模糊?

CSS3 无法反转动画

ios - 在plist中删除数据时显示alertview

ios - 关闭当前 View Controller 回到主视图 Controller 应用程序崩溃 IOS 7

swift - 找不到委托(delegate)方法索引路径

javascript - 使用 Angular 2+ 动画蒙版位置

ios - 尝试在 UITableView 中插入新行时出现格式问题

ios - 在多个项目中使用 CocoaPods