Reputation: 221
I've a UIButton which I built in Storyboard. Its title is "Hallo" (Entered in Attributes Inspector) It is connected via an Outlet. In viewDidLoad I did the following:
self.myButton.hidden = YES;
In another method I want to change the title and make the button visible:
[self.myButton setTitle:@"Test" forState:UIControlStateNormal];
self.myButton.hidden = NO;
Now the strange thing: For a few milliseconds I see the old title "Hallo" and then it changes to "Test". How could this be? I could understand this behaviour if I make it first visible and then change the text.
Upvotes: 6
Views: 1254
Reputation: 1066
I also had the same issue for the button which I put on uitableview cell. Following code was working for me. It's setting the title for all the status of the button.
[self.myButton setTitle:@"Test" forState:forState:UIControlStateNormal|UIControlStateHighlighted|UIControlStateSelected];
self.myButton.hidden = NO;
Upvotes: 2
Reputation: 7534
This is related to How to prevent UIButton from flashing when updating the title. When the button title is changed, the text change seems to be animated. When the title is changed while the button is hidden, that animation may still be in progress, or the animation is delayed until the button is shown.
So if you want to set the title of a button while it's hidden and then show it immediately, you should wrap both actions in a block passed to UIView.performWithoutAnimation
, and call layoutIfNeeded
inside that block:
UIView.performWithoutAnimation {
self.button.setTitle("New Title", for: .normal)
self.button.isHidden = false
self.button.layoutIfNeeded()
}
Upvotes: 0
Reputation: 678
I had the same problem. The only way I could get round it was to change the label to an empty string and disabling the button instead of hiding the button:
self.myButton.setTitle(@"", UIControlState.Normal);
self.myButton.enabled = NO;
Then setting the button text again and enabling it where you're showing it again:
self.myButton.setTitle(@"Test", UIControlState.Normal);
self.myButton.enabled = YES;
Upvotes: 0
Reputation: 2369
Check your title for highlighted state of your button too
[self.myButton setTitle:@"Test" forState:UIControlStateNormal];
[self.myButton setTitle:@"Test" forState:UIControlStateHighlighted];
self.myButton.hidden = NO;
Upvotes: 1
Reputation: 1274
I think the second part is called during the touch up of this button. A solution :
[self.myButton setTitle:@"Test" forState:UIControlStateNormal];
[self.myButton setTitle:@"Test" forState:UIControlStateSelected];
self.myButton.hidden = NO;
Upvotes: 0