user401383
user401383

Reputation: 401

UIButton setText programmatically

I have about 10 UIButtons on xib file and want to setText programmatically

Upvotes: 40

Views: 46301

Answers (3)

Md Imran Choudhury
Md Imran Choudhury

Reputation: 10057

In Swift 3+:

button.setTitle("Button Title", for: .normal)

Otherwise:

button.setTitle("Button Title", forState: UIControlState.Normal)

Upvotes: 8

Jorge Arimany
Jorge Arimany

Reputation: 5882

I think you could create a collection of buttons from your layout:

Select the first button from your xib and drag it with the right button into your code: Drag firs button

then you should select "Outlet Collection" for the Connection type and assign a name:

select Outlet collection

Then in your code you have an array of buttons from your xib file:

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttons;

Next select and drag the other buttons over the created collection, do it one by one in the order you want to iterate them: Drag the other buttons

You can check the order of the buttons in the connections inspector hovering over the array you have created: check button order

Now set each button text:

for (int i = 0; i<self.buttons.count; i++) {
    UIButton * button = self.buttons[i];
    [button setTitle: [NSString stringWithFormat:@"Button %d",i ] forState:UIControlStateNormal];
}

Note that UIControlStateNormal is the default state and if not overridden it will be shown for all states:

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.

I hope that helps

Upvotes: 2

Ron Srebro
Ron Srebro

Reputation: 6862

You might want to be more specific next time you ask a question.

You can try assign a different tag for each button in interface builder (or the same tag if thats what you need) and then use the following code

for (int i = 1 ; i<=10;i++)
{
     UIButton *myButton = (UIButton *)[myView viewWithTag:i];
     [myButton setTitle:@"my text" forState:UIControlStateNormal];
}

Upvotes: 62

Related Questions