在我的应用程序中,我正在尝试使用按钮创建一个按钮。我现在的代码如下:
- (IBAction)doneTextField:(id)sender {
YourShortcutsViewController *YSVC2 = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewController2"];
YSVC2.stringFromTextField = self.textField.text;
[self presentViewController:YSVC2 animated:YES completion:nil];
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn addTarget:self action:@selector(newButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:@"FaceTime" forState:UIControlStateNormal];
[self.view addSubview:btn];
}
}
这有效,但我需要添加的按钮添加到不同的视图控制器中,而不是代码所在的视图控制器。 我该怎么办? 谢谢
答案 0 :(得分:2)
您需要创建一个函数来在新视图控制器中添加按钮:
在YourShortcutsViewController.h中:
-(void)addFaceTimeButton:(UIButton*);
在YourShortcutsViewController.m中:
-(void)addFaceTimeButton:(UIButton*){
[self.view addSubview:btn];
}
然后将您的代码更改为:
- (IBAction)doneTextField:(id)sender {
YourShortcutsViewController *YSVC2 = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewController2"];
YSVC2.stringFromTextField = self.textField.text;
[self presentViewController:YSVC2 animated:YES completion:nil];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 50);
[btn addTarget:self action:@selector(newButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:@"FaceTime" forState:UIControlStateNormal];
[YSVC2 addFaceTimeButton:btn];
}