is it possible to update UIButton title/text programmatically?

后端 未结 12 1755
北海茫月
北海茫月 2020-12-07 19:58

I have a UIButton, that when pressed, brings up a new view where the user can change some settings. When the view is dismissed, I\'d like to update the title/t

相关标签:
12条回答
  • 2020-12-07 20:12

    for swift :

    button.setTitle("Swift", forState: UIControlState.Normal)                   
    
    0 讨论(0)
  • 2020-12-07 20:18

    Turns out the docs tell you the answer! The UIButton will ignore the title change if it already has an Attributed String to use (with seems to be the default you get when using Xcode interface builder).

    I used the following:

    [self.loginButton 
         setAttributedTitle:[[NSAttributedString alloc] initWithString:@"Error !!!" attributes:nil] 
         forState:UIControlStateDisabled];
    [self.loginButton setEnabled:NO];
    
    0 讨论(0)
  • 2020-12-07 20:20

    As of Swift 4:

        button.setTitle("Click", for: .normal)
    
    0 讨论(0)
  • 2020-12-07 20:22

    One more possible cause is this:

    If you attempt to set the button's title in the (id)initWithNibName: ... method, then you're button property will still be nil. It hasn't yet been assigned to the UIButton.

    You must be sure that you're setting your buttons in a method like (void)viewWillLoad or (void)viewWillAppear, but you probably don't want to set them as late as (void)viewDidAppear.

    0 讨论(0)
  • 2020-12-07 20:23

    Do you have the button specified as an IBOutlet in your view controller class, and is it connected properly as an outlet in Interface Builder (ctrl drag from new referencing outlet to file owner and select your UIButton object)? That's usually the problem I have when I see these symptoms.


    Edit: While it's not the case here, something like this can also happen if you set an attributed title to the button, then you try to change the title and not the attributed title.

    0 讨论(0)
  • 2020-12-07 20:25

    I discovered another problem. It may be a bug introduced in iOS 5, but I thought I'd point it out for anyone else who encounters it.

    If you don't set any default text for the button in the XIB, no text will ever appear if you set it programmatically. And if you do set text in the XIB, any text you subsequently assign to the button programmatically will be truncated to the size of the default text.

    And finally, if you're showing the view with your button and then invoke another view (like an ActionSheet) and then dismiss it, the text that you assigned to the button programmatically will be erased and the button caption will return to whatever you set up in the XIB.

    0 讨论(0)
提交回复
热议问题