How to cross out a button between a selected and unselected state in xcode?

I have two images for the button: one for the normal state and one for the selected state. When I switch from the selected state to the normal state, I would like this to happen with the crossfade effect within a few seconds.

What I'm doing so far is using two UIView animations: the first of the alpha version 1.0 in the alpha .5 file in the selected state. Then I switch to normal and execute a second UIView animation, going from alpha .5 to alpha 1.0.

I am not happy with the visual effect (a sharp transition from the selected to the normal image). I also read that UIView should no longer be used. So what is the right approach here? Sample code is also very useful.

+4
source share
3 answers

Finally, I found what I need: instead of assigning images to the selected and unselected states of my button, I keep my button transparent and add two views to this button instead, first with alpha 1.0 and 0.0.

When the button is selected and I enter the method specified in the selector, I use the animation to switch between the two views as follows:

NSArray * subviewArray = [button subviews]; [UIView animateWithDuration:2.0 animations:^ { ((UIView *)[subviewArray objectAtIndex:0]).alpha = 0.0; ((UIView *)[subviewArray objectAtIndex:1]).alpha = 1.0; } completion:nil]; 

This approach also works if the button moves during the transition. Hope this helps others who face the same issue in the future!

+1
source

The following is quite simple and will go from the selected to the unselected state in 4 seconds. The only problem is that the transition does not work when the button also moves at the same time.

  button.selected = TRUE; CATransition *transition = [CATransition animation]; transition.duration = 4.0; transition.type = kCATransitionFade; transition.delegate = self; [button.layer addAnimation:transition forKey:nil]; button.selected = TRUE; 
+1
source

For me it worked:

 [UIView transitionWithView: button duration: 4.0 options: UIViewAnimationOptionTransitionCrossDissolve animations: ^{ [button setSelected: !button.isSelected]; } completion: nil]; 

But this one only worked when I installed the same UIImage in UIControlStateHighlighted and UIControlStateSelected with these three following calls (leaving one call did not work for me):

 [button setImage: img forState: UIControlStateSelected | UIControlStateHighlighted]; [button setImage: img forState: UIControlStateSelected]; [button setImage: img forState: UIControlStateHighlighted]; 
0
source

Source: https://habr.com/ru/post/1343117/


All Articles