如何在另一个视图控制器中侦听didSelectRowAtIndexPath更改

时间:2013-02-01 13:24:19

标签: iphone ios objective-c uitableview

我想倾听/检测didSelectRowAtIndexPath:中的viewController1更改,然后根据此选择更改viewController2中的内容。

知道我该怎么做才能做到这一点?

1 个答案:

答案 0 :(得分:5)

使用KVO。

首先在ViewController1.h中创建一个@property:

@property (strong, nonatomic) NSIndexPath *selectedIndexPath;

在ViewController1.m中:

@synthesize selectedIndexPath;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath!=self.selectedIndexPath) self.selectedIndexPath = indexPath; //this will fire the property changed notification

在ViewController2.m中,假设您已经引用了ViewController1(即vc1),请在viewDidLoad中设置Observer:

-(void)viewDidLoad
{
     [super viewDidLoad];
     [vc1 addObserver:self forKeyPath:@"selectedIndexPath" options:NSKeyValueObservingOptionNew context:NULL];
     //other stuff

最后在ViewController2中添加以下内容

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //inspect 'change' dictionary, fill your boots

    ...
}

ETA:

您还必须删除ViewController2的dealloc中的观察者:

-(void)dealloc
{
    [vc1 removeObserver:self forKeyPath:@"selectedIndexPath"];
    ...
}