Share on Google+Share on Google+

UIButton setTitle:forState:

Advertisement
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?

UIButton setTitle:forState:

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.

Download Code

Advertisements

Advertisement

Posted on: September 22, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.