简体   繁体   中英

UIControl.State.Highlighted image on UIButton only works after first touch event

I have a set of buttons I'd like to have crossfade through a different highlighted image than normal when touched. The technique below works fine, but only after the second touch event on the same button. The first touch produces the standard "faded dark grey" on the whole button; from then on future touches it crossfades correctly through the pictures on highlight.

I've only tested this in the simulator, is that he issue? If not, how do I produce the correct highlighted state on every touch? Thanks!

@IBOutlet weak var someButton: UIButton!       
@IBAction func someButton(_ sender: UIButton) {

    UIView.transition(with: sender, duration: 0.3, options: .transitionCrossDissolve, animations: {
        sender.setImage(UIImage(named: "My Image.png"), for: UIControl.State.highlighted)
    }, completion: nil)

//...other functions

}

Set the button's highlighted image initially at the time of setting up UIButton properties or in viewDidLoad() by writing the code below.

yourButton.setImage(UIImage(named: "My Image.png"), for: UIControl.State.highlighted)

Reason for not working your code

The button action @IBAction func someButton(_ sender: UIButton) always call only on release of the user's finger so by this time UIButton doesn't has the image for the highlighted state for the first time. Later on, the image is set through animation so it is animating perfectly.

Edit

You can make transition of UIButton with firebase call or some other event action by creating a separate function like shown below. Use the UIButton 's outlet to access the button.

@IBOutlet weak var someButton: UIButton!

func buttonTransition() {

    UIView.transition(with: sender, duration: 0.3, options: .transitionCrossDissolve, animations: {
        someButton.setImage(UIImage(named: "My Image.png"), for: UIControl.State.highlighted)
    }, completion: nil)
}

So, you can call buttonTransition() function from wherever you want.

It is working on the second click because you have written the transition code inside the button click action. Just write that code in the viewDidLoad or viewWillApear and it will work before the first click and will set the transition on the button. Write something like this in viewDidLoad:

 override func viewDidLoad() {
    super.viewDidLoad()
    UIView.transition(with: button, duration: 0.3, options: .transitionCrossDissolve, animations: {
        self.button.setImage(UIImage(named: "image.png"), for: UIControl.State.highlighted)
    }, completion: nil)
}

here button is the outlet variable of the button created in storyboard.

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