序言:
我们项目中会遇到自定义cell,然后点击cell中button把值push到下一页面,或者点击该button让cell伸展通过改变cell的高度,这时问题就来了,我怎么知道我点击的是哪一行cell的button,一共有三种实现方式
1.button添加tag
在代理方法给cell的button添加tag
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
ATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aCell" forIndexPath:indexPath];
cell.pushButton.tag = indexPath.row;
cell.delegate = self;
return cell;
}
点击button,直接取button的tag就ok
BViewController *b = [self.storyboard instantiateViewControllerWithIdentifier:@"B"];
b.str = [NSString stringWithFormat:@"俺从第%ld过来的",button.tag];
[self.navigationController pushViewController:b animated:YES];
}
2.根据point取indexpath
为button添加点击方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
ATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aCell" forIndexPath:indexPath];
[cell.pushTwoButton addTarget:self action:@selector(pushTwo:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
indexPathForRowAtPoint方法实现
-(void)pushTwo:(UIButton *)sender{
CGPoint point = sender.center;
point = [self.tableView convertPoint:point fromView:sender.superview];
NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
BViewController *b = [self.storyboard instantiateViewControllerWithIdentifier:@"B"];
b.str =[NSString stringWithFormat:@"俺从第%ld过来的",indexpath.row];
[self.navigationController pushViewController:b animated:YES];
}
3.让controller成为cell的代理把cell 传到controller
@class ATableViewCell;
@protocol ATableViewCellDelegate<NSObject>
@optional
-(void)pushThree:( ATableViewCell*)cell;
@end
@interface ATableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *pushButton;
@property (weak, nonatomic) IBOutlet UIButton *pushTwoButton;
@property(nonatomic,weak)id<ATableViewCellDelegate>delegate;
@end
- (IBAction)pushThree:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:@selector(pushThree:)]) {
[self.delegate pushThree:self];
}
}
再在代理方法中通过indexPathForCell实现
-(void)pushThree:(ATableViewCell *)cell{
NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
BViewController *b = [self.storyboard instantiateViewControllerWithIdentifier:@"B"];
b.str =[NSString stringWithFormat:@"俺从第%ld过来的",indexPath.row];
[self.navigationController pushViewController:b animated:YES];
}
网友评论