开发者

UIButton setText programmatically

I have about 开发者_如何学Python10 UIButtons on xib file and want to setText programmatically


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];
}


In Swift 3+:

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

Otherwise:

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


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:

UIButton setText programmatically

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

UIButton setText programmatically

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:

UIButton setText programmatically

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

UIButton setText programmatically

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜