代码改变世界

如何在cell内部操作控制器的一些行为

2016-11-21 11:12  TemptationM  阅读(510)  评论(0)    收藏  举报

场景:

比如cell内部存在button, 或者cell内部嵌套一个collectionView, 此时在点击cell上的button或者collectionView的item时,希望控制器进行跳转之类的行为

(当然使用代理模式也能实现,在这里记录一下另一种方式)

 

思路:将target和SEL(action)传递到cell内部, 用 - (id)performSelector:(SEL)aSelector withObject:(id)object;方法, 达到在cell内调用方法,但在控制器中实现

 

1、在cell的.h文件中

- (void)setTarget:(id)target action:(SEL)action;

 

2.在cell的.m文件中添加两个属性

@property (weak, nonatomic) id target;

@property (assign, nonatomic) SEL action;

 

//在.m中实现.h的方法

- (void)setTarget:(id)target action:(SEL)action

{

  self.target = target;

  self.action = action;

}

//在cell中button的触发方法中或在cell的collectionView的didSelectItemAtIndexPath方法中调用方法

- (void)xxxxxxxxxxxxxx

{

  if(self.target && self.action)

  {

  [self.target performSelector:self.action withObject:indexPath];//这里可以带参数

  }

}

 

3. 这时便可在控制器中创建cell的时候 将cell调用自己的方法

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath

{

  xxxcell *cell = [tableView dequeueReusableCellWithIdentifier:  forIndexPath:];

  [cell setTarget:self action:@selector:(push:)];

}

- (void)push:(xxxcell*)sender  //sender即为cell中传的参数

{

  [self.navigationController pushViewController:xxVC animated:YES];

}

 

就这样达到了想要的效果, 在cell内部操作控制器的一些行为!