简体   繁体   中英

Working UIButton animations in Swift

I've been trying to get this snippit of code to work but I can't seem to get my UIButton to animate through images.

@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();
    }

After writing this code I've dragged a line from screenButton to the button I want to animate through the image in the Storyboard. What am I doing wrong?

What you need to do is to not re-initialize the UIButton in the function animation ; so, comment out this line:

//var animationButton : UIButton!

Besides just having an IBOutlet , we need also an IBAction to your function animation . Do the same thing as you do for your button by control dragging a "line" to the block of function (check IBAction , not IBOutlet ).

A little walk-through while you are still in storyboard:


  • What you have is only one button named: animationButton , which is an IBOutlet from your storyboard to your code by control-dragging a "line".

  • For your animation function: Control-drag also from storyboard from the button a "line" to the block of the animation function.

  • Set up an initial image for you button in storyboard as will be mentioned shortly below.

In addition, we need to set up an initial image in storyboard; otherwise, the image property of the button is nil .

Please do so in storyboard by clicking on the right hand side "Attributes Inspector" and then set an image where it says "image". As test, I set that up as "1.jpg".

Thus, you code should look like the following:

@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()
}

Just ran a quick test; it gets touch event and the images animate on the button. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM