ios - 以编程方式创建按钮以转到下一个 View 时如何在 View 中传递数据?

标签 ios objective-c

我在 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/

相关文章:

ios - 为什么我的 Print 语句没有被执行?

ios - 在不使用 Xamarin 中的默认/内置应用程序的情况下在 iOS 和 Android 中发送电子邮件

ios - 使用键盘和中心自动布局管理 View

iphone - 动态创建 uiImageView

ios - 在 TableView 或 Collection View 中删除与 IndexPath 关联的 CKRecord 的可靠方法是什么?

ios - SearchController 不显示导航栏

ios - Woo-Commerce REST API 响应在 Postman 上正确而不是在 Xcode 中

ios - Contact Framework 仅抓取少量联系人

objective-c - 使用 Objective-C,有没有办法将树转换为快速枚举?

objective-c - 可以在 Cocoa 中创建没有按钮的 NSAlert