Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting titleLabel for UIButton

I was a little confused to find today that the following does not work when trying to change the text shown on a UIButton.

// 001
[[[self button] titleLabel] setText:@"Peanuts"];

I think I know why, but I just wanted to confirm my thinking here. 001 does set the titleLabel text property, but as its a UILabel (a subview of the UIButton) it does not cause the UI to be redrawn. This results in an internal change to the UILabel text property, but sadly no visual change in the UI.

// 002
[[self button]setTitle:@"Peanuts" forState:UIControlStateNormal];

It would seem that the method setTitle:forState is the correct way to go, it has the extra overhead of requiring a state but does invoke a UI redraw because its being called directly on the UIButton. My question is, is 002 the correct way to do this, it would seem it is unless I am doing something totally wrong?

like image 487
fuzzygoat Avatar asked Sep 04 '12 14:09

fuzzygoat


People also ask

How do I change the Textcolor button in Swift?

To change a button's text color in SwiftUI we need to use . foregroundColor on our text view. In the above code it is almost the same as the simple button, but we used a modifier to change the foregroundColor to green.

How do I change the label text on a button click in Swift?

Open your storyboard and view controller source side by side in the assistant editor. Then select the label. Switch to the connections inspector and then drag from the small circle next to "New Referencing Outlet" and into the view controller source file. This should create the @IBOutlet for you.


1 Answers

You are correct.

[[self button]setTitle:@"Peanuts" forState:UIControlStateNormal];

is the way button titles should be set. This allows you to control what your button looks like in all of its different control states.

From the docs:

In general, if a property is not specified for a state, the default is to use the UIControlStateNormal value. If the value for UIControlStateNormal is not set, then the property defaults to a system value. Therefore, at a minimum, you should set the value for the normal state.

like image 102
Mick MacCallum Avatar answered Sep 24 '22 20:09

Mick MacCallum