Passing button title to a new view
I have a button on a view which when pressed开发者_JS百科 opens another second view. I want to set a label in the second view to change depending on the label of the button that was pressed. I have tried passing (id) sender in my switchViews function but that does not work. Please help!
On your second view controller, create a the UILabel as a property i.e.
@interface MyViewcontroller : UIViewController {
UILabel *titleLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *titleLabel;
and, in interface builder, attach it to the label that you want to change.
Then, in your first view controller's switchViews method, after you create your second view you can set the title like this :
...
MyViewController *newViewController = [[MyViewController alloc] initWithNibName:'something' bundle:nil];
newViewController.view.titleLabel.text = @"Your new title goes here";
...
Hope that helps.
Passing sender should work. Just cast sender to UIButton * and take title for the state with titleForState:. Here is working code:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window makeKeyAndVisible];
UIButton * myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(100, 100, 100,80);
[myButton setTitle:@"test title" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[window addSubview:myButton];
}
- (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];
}
精彩评论