将属性传递给UITableViewController的最简单方法

时间:2012-01-06 23:17:14

标签: objective-c xcode

我有两个UITableViewControllers(连接到UINavigationController)。当我在第一个控制器上单击UITableViewCell时,我创建了一个segue,以便第二个控制器进入视图。我想在第二个视图控制器中有一个变量,其中包含所选文本。我该怎么做呢?我试过直接传递它,但由于某种原因它不起作用。

1 个答案:

答案 0 :(得分:0)

在接收视图控制器上声明一个属性(如selectedText - NSString)(在本例中我们称之为SecondTableViewController)。这是代码:

在SecondTableViewController.h中:

@interface SecondTableViewController : UITableViewController {

}

@property(nonatomic, strong) NSString *selectedText;

在SecondTableViewController.m中:

@implementation SecondTableViewController
@synthesize messageDetail;

在你的FirstTableViewController.m中:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure we are dealing with the proper Segue
    if ([segue.identifier isEqualToString:@"idOfMySegue"]) {
        SecondTableViewController *svc = segue.destinationViewController;
        svc.selectedText = myVarValue; // This can be got from either setting another var in the tableviewcontroller or by just passing the entire object at the selected index of the NSIndexPath.row (if you are populating the tableview with an array.  Note you would change the object type of the passed along object from an NSString to whatever the other object is.
    }
}

prepareForSeque方法是您将任何数据或对象从一个视图传递到另一个视图的地方。