Thursday, May 30, 2013

UIButton titleForState example in Objective C (iOS).

UIButton titleForState

Returns the title associated with the specified state.

- (NSString *)titleForState:(UIControlState)state

Parameters
state
The state that uses the title. The possible values are described in UIControlState.

Return Value of [UIButton titleForState]
The title for the specified state. If no title has been set for the specific state, this method returns the title associated with the UIControlStateNormal state.

UIButton titleForState example.
- (void)myButtonClicked:(id)sender{
    UIButton * clickedButton = (UIButton *)sender;
    NSString * buttonTitle = [clickedButton titleForState:UIControlStateNormal];
    NSLog(@"title: %@",buttonTitle);
    UILabel * myLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 250, 100,80)];
    myLabel.text = buttonTitle;
    [window addSubview:myLabel];
}

Example of [UIButton titleForState].
//Right-align the button image
CGSize size = [[myButton titleForState:UIControlStateNormal] sizeWithFont:myButton.titleLabel.font];
[myButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -size.width)];
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, myButton.imageView.image.size.width + 5)];

UIButton titleForState example.
-(void)changeButton:(NSString*)button withURL:(NSString*)url {
timetableURL = url;

UIImage *btnImage;

if ([button titleForState:UIControlStateNormal] isEqualToString:@"Safari"]) {
    btnImage = [UIImage imageNamed:@"browser-button.png"];
    [safariBtn addTarget:self action:@selector(onSafariButtonPress:) forControlEvents:UIControlEventTouchUpInside];
}
else if ([button titleForState:UIControlStateNormal] isEqualToString:@"Timetable"]) {
    btnImage = [UIImage imageNamed:@"browser-timetable.png"]; 
    [safariBtn addTarget:self action:@selector(onTimetableButtonPress:) forControlEvents:UIControlEventTouchUpInside];
}

[safariBtn setImage:btnImage forState:UIControlStateNormal];
[btnImage release];
}

End of UIButton titleForState example article.