关于UITableView选中效果以及自定义cell上的控件响应事件

时间:2023-01-01 18:03:21

tableView默认的点击效果是:点击cell:A,出现点击效果,点另一个cell:B的时候,A的点击效果才会消失。

1、对于tableView,比较常用的效果,是点击表格行,出现效果,点击完毕,效果消失

那么就要在代码里做一些设置。代码如下:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

2、还有一种情况也是比较常用的,每个表格单元加上两个button,我们不想让表格行点击时出现效果,只是点击button的时候有效果,那么就要设一下cell的样式

industryCell.selectionStyle = UITableViewCellAccessoryNone;

这样,点击cell的时候整个cell就不会出现点击效果了。

3、当我们需要在cell上加button,并让button响应事件时,应该在

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

方法中获取cell上的button:

firstButton,然后给其加上响应事件

实现如下:

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

{

    NSString *cellIndentifier = @"CellIndentfier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];//cell是在storyBoard里创建的,所以直接获取就好

    cell.selectionStyle = UITableViewCellAccessoryNone;//让整个cell点击无效果

 

    UIButton *firstButton = (UIButton *)[cell viewWithTag:kCell_ButtonTag_1];

    [firstButton addTarget:self action:@selector(gradeBtnPressed:) forControlEvents:UIControlEventTouchUpInside];

     return cell;

}

 

最主要的应该是firstButton的响应事件

-(void)gradeBtnPressed:(id)sender

{

    UITableViewCell * cell = (UITableViewCell *)[[[sender superview] superview] superview];//根据button加在cell上的层次关系,一层层获取其所在的cell(我的层次关系是:cell-》ImageView—》Label-》Button,所以要获取三次取得cell)

    NSIndexPath * indexPath = [self.onlineListTableView indexPathForCell:cell];//获得cell所在的表格行row和section

    UIButton *button = (UIButton *)sender;

}

4、总结

自定义cell,会有许多效果,持续学习中,学习