Passing button title to a new view

萝らか妹 提交于 2019-12-12 03:58:20

问题


I have a button on a view which when pressed 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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2385876/passing-button-title-to-a-new-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!