is it possible to update UIButton title/text programmatically?

后端 未结 12 1756
北海茫月
北海茫月 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:06

    I solved the problem just setting the title parameter for UIControlStateNormal, and it automatically works on the other states. The problem seems to be when you set another UIControlState.

    [myButton setTitle: @"myTitle" forState: UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-07 20:08

    Make sure you're on the main thread.

    If not, it will still save the button text. It will be there when you inspect the object in the debugger. But it won't actually update the view.

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

    I kept having problems with this, the only solution was to add an image and label as subviews to the uibutton. Then I discovered that the main problem was that I was using a UIButton with title: Attributed. When I changed it to Plain, just setting the titleLabel.text did the trick!

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

    Even though Caffeine Coma's issue was resolved, I would like to offer another potential cause for the title not showing up on a UIButton.

    If you set an image for the UIButton using

    - (void)setImage:(UIImage *)image forState:(UIControlState)state
    

    It can cover the title. I found this out the hard way and imagine some of you end up reading this page for the same reason.

    Use this method instead

    - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
    

    for the button image and the title will not be affected.

    I tested this with programmatically created buttons and buttons created in a .xib

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

    Sometimes it can get really complicated. The easy way is to "refresh" the button view!

    //Do stuff to your button here.  For example:
    
    [mybutton setEnabled:YES];
    
    //Refresh it to new state.
    
    [mybutton setNeedsDisplay];
    
    0 讨论(0)
  • 2020-12-07 20:10

    @funroll is absolutely right. Here you can see what you will need Make sure function runs on main thread only. If you do not want deal with threads you can do like this for example: create NSUserDefaults and in ViewDidLoad cheking condition was pressed button in another View or not (in another View set in NSUserDefaults needed information) and depending on the conditions set needed title for your UIButton, so [yourButton setTitle: @"Title" forState: UIControlStateNormal];

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