OStack程序员社区-中国程序员成长平台

标题: ios - 如何在objective-c中的 View Controller 之间传递数据? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:34
标题: ios - 如何在objective-c中的 View Controller 之间传递数据?

选择项是一个 slider 。当我单击 slider 时,它会将数据传递给第二个 VC(WebViewController)。但是如何在objective-c中将数据从第一个 View Controller 传递到第二个 View Controller ?抱歉,这是我第一次编写 Objective-C 。

第一个 VC .m 文件

#import "WebViewController.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    arraySliderProducts = [[NSMutableArray alloc]init];
}


- (void)collectionViewUICollectionView *)collectionView didSelectItemAtIndexPathNSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];

    UIViewController *controller = nil;


    switch (indexPath.row)
    {

        case 0:
        {
            WebViewController *WebViewController = [[WebViewController alloc] init];
            //error: No visible @interface for "WebViewController" declares the selector 'alloc'
            WebViewController.data = arraySliderProducts[indexPath.row][@"title"]; //pass this link value
            //error: Property 'data' not found on object of type 'WebViewController'
            [self.navigationController pushViewController: WebViewController animated:YES];
        }..

第二个 VC .m 文件

@interface WebViewController ()
@property (nonatomic, retain) NSString *data;

第二个 VC .h 文件

#import <UIKit/UIKit.h>

@interface WebViewController : UIViewController
{
    AppDelegate *appDelegate;
    NSString *data;
}
@end



Best Answer-推荐答案


注意两点:

1:这不是启动 View Controller 以在您的应用中显示/呈现的方式。

2:您应该在您的 SecondVC 的 .h 文件中声明您的 NSString *data

现在第 1 点解决方案是在您的 didSelectItemAtIndexPath 中更改您的代码:函数

switch (indexPath.row)
{
    case 0:
    {
        // By Default storyboard name is "Main". Change it if you you have different name in your project
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName"Main" bundle: nil];

        // Now instantiate your view controller with its identifier on this storyboard object. 
        // Note: don't forget to set viewControllers' identifier
        WebViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"WebViewController"];

        // Now Pass your value 
        WebViewController.data = arraySliderProducts[indexPath.row][@"title"]; 

        //Finally push this object on your navigation stack
        [self.navigationController pushViewController: WebViewController animated:YES];
    }... 
}

关于ios - 如何在objective-c中的 View Controller 之间传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108639/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4