最近,做项目的时候,需要在自定的table cell上添加按钮,结果发现设置的按钮点击事件不好用,之前的项目也做过类似功能,但是因为那个时候是刚接触ios,所有采用的是添加代理的方式。上网查了资料,发现原因的是因为ios 7 之后在cell中添加的按钮,实际上是添加在cell的scrollView上, 由于IOS7中添加了滑动后出现编辑按钮的操作,所以使用scrollView来处理,UITableViewCellScrollView有对触摸的相应处理,导致按钮的点击效果被屏蔽了,但是点击事件还是在的。使用网上介绍的方法: ---(不好用,也许是我的方法不对)
1.设置tableView.delaysContentTouches = NO;
2.同时在(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath代理方法中对scrollview把延迟触摸设置为NO即可。
真正解决问题的方法是:在- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中往cell添加按钮。
相关代码:
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
static NSString *Contentidentifier = @"CommonOrderCell";
LotteryOrder *order = [dataList objectAtIndex:row];
UINib *nib = [UINib nibWithNibName:Contentidentifier bundle:nil];
[atableView registerNib:nib forCellReuseIdentifier:Contentidentifier];
CommonOrderCell *cell=[atableView dequeueReusableCellWithIdentifier:Contentidentifier];
//cell.lblHandleTime.text = [NSString stringWithFormat:@"%@", order.handleOrderTime];
cell.lblLotteryType.text = [NSString stringWithFormat:@"%@", order.lotteryTypeDesc];
cell.lblMoney.text = [NSString stringWithFormat:@"%1g元", order.money];
cell.lblProjectNum.text = [NSString stringWithFormat:@"%@", order.projectNumber];
UIButton *btnRobOrder = [UIButton buttonWithType:UIButtonTypeCustom];
[btnRobOrder setFrame:CGRectMake(226, 90, 60, 30)];
[btnRobOrder setBackgroundColor:[UIColor colorWithRed:(21.0/255.0) green:(136.0/255.0) blue:(238.0/255.0) alpha:1]];
btnRobOrder.layer.cornerRadius = 5.0;
[btnRobOrder.titleLabel setFont:[UIFont systemFontOfSize:13.0]];
[btnRobOrder setTitle:@"抢约" forState:UIControlStateNormal];
[btnRobOrder setTag:row];
[btnRobOrder addTarget:self action:@selector(robOrderBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btnRobOrder];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
点击事件相关代码:(通过tag去取到相映的数据)
-(void) robOrderBtnClick:(id) sender
{
UIButton *button = (UIButton *)sender;
NSInteger index = button.tag-1;
NSString *orderId = [[dataList objectAtIndex:index] orderId];
}
注:
IOS6的UITableViewCell 子视图(subviews)的容器是UITableViewCellContentView
IOS7的UITableViewCell 子视图(subviews)的容器是UITableViewCellScrollView