我在 ViewController 中以编程方式创建了一个按钮。当用户点击这个按钮时,它会转到一个名为 SecondViewController 的新 View Controller 。在 Storyboard 中使用 segues,我知道如何在 View Controller 之间传递数据,并且在过去已经做到了。
我的问题:如果我不使用 Storyboard 并以编程方式执行此操作,我该怎么做?
SecondViewController 有一个名为 data 的 NSString 属性。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//load the street view container
if ([[segue identifier] isEqualToString:@"firstToSecond"]) {
//send coordinates to container
SecondViewController *embed = segue.destinationViewController;
embed.data = @"test";
}
}
- (void)aMethod:(UIButton*)button
{
NSLog(@"Button clicked.");
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
[self.navigationController pushViewController: myController animated:YES];
//I get an error on these 2 lines of code within Xcode.
MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:@"firstToSecond" source:self destination:SecondViewController];
[self prepareForSegue:segue sender:sender];
[segue perform];
}
在 xcode 中,我在这 2 行中收到错误:
MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:@"firstToSecond" source:self destination:SecondViewController];
[self prepareForSegue:segue sender:sender];
有什么建议吗?
最佳答案
如果您想使用 [self.navigationController pushViewController:myController animated:YES]
将 viewController 添加到层次结构中您不需要以编程方式创建 segue。prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
在destinationViewController 被推送之前调用,让您有机会在它出现在屏幕上之前修改或传递数据给它。所以不要手动调用这个函数。您需要做的就是将您的代码从那里移动到两者之间
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
myController.data = @"test";
[self.navigationController pushViewController: myController animated:YES];
关于ios - 以编程方式创建按钮以转到下一个 View 时如何在 View 中传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132539/