免费开源的iOS开发学习平台

UITableView详解:5-代理方法之点击单元格

在UITableView中的每个单元格Cell,都可以监听用户的点击动作,并可以通过代理方法来进行一些逻辑处理。常见的操作有:选中某一个单元格后,能够跳转到另外一个控制器,显示详细信息,例如微信、QQ的对话即为如此。

UITableView监听用户点击动作的常用方法

UITableView的代理方法中,可以完整的监听到用户点击动作,包括即将点击,完成点击等。在这些代理方法中,我们可以对用户的点击动作进行逻辑处理。

  • 用户点击单元格时调用
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
  • 取消单元格选中调用
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath;
  • 单元格高亮显示
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath;

UITableView监听用户点击动作实例

这个案例主要是为了展现监听用户点击动作各方法调用的时机。为了调用代理方法,我们首先需要记得提前设置UITableView对象的代理对象。

 //通知委托是否开启点击高亮显示
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//通知委托指定行被高亮显示
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"调用tableView:didHighlightRowAtIndexPath:方法");
}
//通知委托指定行不在高亮显示,一般是点击其他行的时候
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"调用tableView:didUnhighlightRowAtIndexPath:方法");
}
//通知委托指定行将要被选中,返回响应行的索引,即可以点击一行而返回另一行索引,如果不想点击事件响应则返回nil。
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"调用tableView:willSelectRowAtIndexPath:%@",indexPath);
    return indexPath;
}
//通知委托指定行将取消选中
- (nullable NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"调用tableView:willDeselectRowAtIndexPath:%@",indexPath);
    return indexPath;
}
//通知委托指定行被选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"调用tableView:didSelectRowAtIndexPath:方法");
}
//通知委托指定行被取消选中
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"调用tableView:didDeselectRowAtIndexPath:方法");
}

运行日志:

  • 点击第一个cell过程中调用的方法;

  • 从第一个cell被选中转为点击第三个cell过程中调用的方法。

示例代码

https://github.com/99ios/8.2.5