我想听/检测一个didSelectRowAtIndexPath:
变化viewController1
,然后根据这个选择改变一些viewController2
。
知道我该怎么做吗?
我想听/检测一个didSelectRowAtIndexPath:
变化viewController1
,然后根据这个选择改变一些viewController2
。
知道我该怎么做吗?
使用 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
...
}
埃塔:
您还必须删除 ViewController2 的 dealloc 中的观察者:
-(void)dealloc
{
[vc1 removeObserver:self forKeyPath:@"selectedIndexPath"];
...
}