博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UITableView勾选效果
阅读量:7237 次
发布时间:2019-06-29

本文共 2020 字,大约阅读时间需要 6 分钟。

如今的APP开发中,UITableView是最常用的控件之一,而UITableView中有个很常见的效果就是勾选效果,这个效果是由UITableViewCell中的accessoryType属性来决定的。

accessoryType中的变量是一个枚举值UITableViewCellAccessoryType,让我们来看一下其中包含的东西。

typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) {

UITableViewCellAccessoryNone, // 不显示任何效果
UITableViewCellAccessoryDisclosureIndicator, // 常用的V形引导图标
UITableViewCellAccessoryDetailDisclosureButton //信息提示+V形引导图标
UITableViewCellAccessoryCheckmark, // 勾选效果
UITableViewCellAccessoryDetailButton //信息图标
};

这几个效果我已经罗列在上面了,今天我们要探讨的,就是```UITableViewCellAccessoryCheckmark```勾选效果。我们要实现的,就是单选一个列表中的信息。有以下几个注意点:- 首先在```- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath``` 方法中实现判断被选中的单元格的功能。记录下之前选择的单元格,并且实时更新。 - 其次,解决单元格的复用问题。不然当单元格复用时,会显示多个勾选的BUG。看了一下网上分享的很多的方法,都没有解决单元格复用的问题,或者问的很笼统。 好了,解释的差不多,下面来上代码。 首先我们先声明一个变量,用来存储被选择的行数的标志

@property (nonatomic, strong) NSIndexPath *selectPath; //存放被点击的哪一行的标志

之后我们实现```- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath```这个代理方法
  • (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    int newRow = (int)[indexPath row];
    int oldRow = (int)(_selectPath != nil) ? (int)[_selectPath row]:-1;
    if (newRow != oldRow) {
    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
    newCell.accessoryType = UITableViewCellAccessoryCheckmark;

    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:_selectPath];  oldCell.accessoryType = UITableViewCellAccessoryNone;  _selectPath = [indexPath copy];

    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

最后看一下怎么在```- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath```中添加一段代码,解决复用问题

if (_selectPath == indexPath) {

cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.roomType = _dataSource[indexPath.row];

至此,单选效果就已经完成,并且不会有单元格复用的问题,代码很简单,也不想过多解释了,不清楚的可以接着问.
 

 

转载于:https://www.cnblogs.com/holyday/p/9099037.html

你可能感兴趣的文章
2018.12.27-dtoj-4089-line
查看>>
10:比较整数大小经典案例
查看>>
ES06--elasticsearch
查看>>
pytorch1.0 用torch script导出模型
查看>>
数据结构(九)查找
查看>>
JAVA常用的集合类
查看>>
Unity3D MainCamera和NGUI UICamera的小插曲
查看>>
gnuWin32-mini-2016.10.30
查看>>
Cassandra博客更新预告
查看>>
Linux 格式化和挂载数据盘
查看>>
mybatis 中 prefix="" suffixOverrides="," prefixOverrides="" suffix=""
查看>>
分类算法三(贝叶斯)
查看>>
栈 后缀表达式
查看>>
ruby学习总结01
查看>>
bzoj 1193
查看>>
mysql Client does not support authentication protocol requested by server; consider upgrading MySQL
查看>>
MapReduce中的map与reduce
查看>>
SGU 188.Factory guard
查看>>
ASP.NET MVC 4 (十二) Web API
查看>>
C# 三种打印方式含代码
查看>>