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

han*_*Dev -1 iphone objective-c uitableview ios

我想倾听/检测一个didSelectRowAtIndexPath:变化viewController1,然后根据这个选择改变一些东西viewController2.

知道我怎么可能这样做吗?

Wil*_*ins 5

使用KVO.

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

@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

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

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

最后在ViewController2中的某处添加以下内容

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

    ...
}
Run Code Online (Sandbox Code Playgroud)

ETA:

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

-(void)dealloc
{
    [vc1 removeObserver:self forKeyPath:@"selectedIndexPath"];
    ...
}
Run Code Online (Sandbox Code Playgroud)