【问题标题】:Passing variables (or similar) to newly loaded view将变量(或类似的)传递给新加载的视图
【发布时间】:2010-08-23 12:16:45
【问题描述】:

我正在为一个小型 iphone 应用程序加载新视图,并且想知道如何将详细信息从一个应用程序传递到另一个应用程序? 我正在从 xml 文件中加载一个充满数据的 tableview,然后单击一个新视图通过以下方式引入:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    SubInfoViewController *subcontroller = [[SubInfoViewController alloc] initWithNibName:@"SubInfoView" bundle:nil];
    [self presentModalViewController:subcontroller animated:YES];
    [subcontroller release];

}

下一步是告诉新加载的视图刚刚加载了哪一行? 任何想法,想法都非常受欢迎,请温柔的大新手......

【问题讨论】:

    标签: objective-c iphone cocoa-touch


    【解决方案1】:

    我通常会创建自己的 init 方法来执行此类操作。我认为传入由 tableView 行表示的相应“模型”对象可能会更好,而不是行号本身,如下所示:

    在 SubInfoViewController.h 中

    @interface SubInfoViewController : UIViewController {
        YourObject *yourObject;
    }
    
    @property (nonatomic, retain) YourObject *yourObject;
    

    然后在 SubInfoViewController.m 中:

    - (SubInfoViewController*)initWithYourObject:(YourObject*)anObject {
       if((self = [super initWithNibName@"SubInfoView" bundle:nil])) {
           self.yourObject = anObject;
       }
       return self;
    }
    

    您可以这样创建和展示它:

    // assuming you've got an array storing objects represented 
    // in the tableView called objectArray
    
    SubInfoViewController *vc = [[SubInfoViewController alloc] initWithYourObject:[objectArray objectAtIndex:indexPath.row]];
    [self presentModalViewController:vc animated:YES];
    [vc release];
    

    这可以很容易地进行调整,以允许您传入任何类型的对象或值(例如,如果您仍想这样做,则为行号)。

    【讨论】:

    • 嗨,我想我几乎明白这一点;)最后一段代码是否会在 InfoViewController 中的 '- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {' 中。米?
    • 是的,没错。该方法将提供选定的行,您可以使用它来索引包含 tableView 中表示的对象的数组。然后,您可以抓取该对象并将其传递给您正在创建的新视图控制器。
    • 嗨,史蒂夫,遇到一个有趣的错误...在“YourObject”之前预期的说明符限定符列表(对不起,如果这个新手的东西......慢慢到达那里)
    • 确保将我的示例代码中对“YourObject”的引用替换为您调用模型对象的任何内容......因此,如果表格视图显示配方成分,它可能是“成分”班级。您需要在两个 UIViewController 子类(显示 tableView 和 SubInfoViewController.h 的那个)的头文件中引用定义这些对象的类 - 也就是说,如果您还没有。
    【解决方案2】:

    在你的视图控制器中添加一个实例变量并声明一个与之对应的属性,所以在你分配之后,初始化它,将它设置为 subcontroller.foo = Blah Blah。

    【讨论】:

    • 类似:SubInfoViewController *subcontroller = [[SubInfoViewController alloc] initWithNibName:@"SubInfoView" bundle:nil]; subcontroller.clickedPath = indexPath; [self presentModalViewController:subcontroller animated:YES]; [子控制器发布];
    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 2011-09-05
    • 2012-04-25
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2016-03-26
    • 2011-10-01
    相关资源
    最近更新 更多