setTitle:forState: is the method of UIButton Class, which is used to set the title of the UIButton for different states. These states could be any from the given list…
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2, // flag usable by app (see below)
UIControlStateApplication = 0x00FF0000, // additional flags available for application use
UIControlStateReserved = 0xFF000000
By default the state is normal.
Syntax of setTitle:forState:
- (void)setTitle:(NSString *)title forState:(UIControlState)state
The "setTitle:forState:" methods takes two parameter "Title" and "State".
Title: is a text that will be displayed on the UIButton for the given state, where as the "State" is the current form of the control. For example a button could be in any form selected or normal. The UIButton will always display the title for assigned state.
See the example below…
- (void)myButton
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(ButtonPressed:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"My Button" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
}
-(void)ButtonPressed:(id)sender
{
// here you can access the object which triggered the method
// for example you can check the tag value
NSLog(@"hello!!");
}
In the above example, the UIButton title is set for the state normal …so it'll show the title once the button get loaded.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.