Nesard
Nesard

Reputation: 21

Fade (transition effect) on Swift image button

I have a UIButton with a Default State and a Highlighted State, so when it is in default state it shows image.png, and when is clicked it shows imageOn.png.

The only thing that changes between this to images is the background color.

The thing I haven't be able to do is to make a fade between this two images when the button is clicked, to make a fancy background color change. I'm using Swift.

Upvotes: 2

Views: 1875

Answers (1)

Mr UziBazooka
Mr UziBazooka

Reputation: 222

Well i dont have time to test this right now, but i think you code should look something like this.

override func viewDidLoad() {

let normalImage = UIImage(named: "image.png") as UIImage!
let selectedImage = UIImage(named: "imageOn.png") as UIImage!

var mybutton:UIButton  = UIButton.buttonWithType(UIButtonType.System) as UIButton

mybutton.setTitle("Your title", forState: UIControlState.Normal)
mybutton.frame = CGRectMake(0, 0, 100, 44)

self.view.addSubview(button as UIView)
//set normal image 
mybutton.setImage(normalImage, forState: UIControlState.Normal)
//set highlighted image 
mybutton.setImage(selectedImage, forState: UIControlState.Selected)

mybutton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

}

func buttonClicked(sender:UIButton)
{

if (sender.selected)  { 
    UIView.animateWithDuration(1.5, animations: {
        self.normalImage.alpha = 1.0
        self.selectedImage.alpha = 0.0
    sender.selected = !sender.selected; 
}
else{  
    UIView.animateWithDuration(1.5, animations: {
        self.normalImage.alpha = 0.0
        self.selectedImage.alpha = 1.0  
}

}

Good luck!

Upvotes: 3

Related Questions