iOS开发tableView实现单选和复选

iOS开发中,有时候需要实现tableView中cell的单选或者复选,这里举例说明了怎么简单的实现

首先自己创建一个列表,实现单选,先定义一个变量记录每次点击的cell的indexPath:

@property (assign, nonatomic) NSIndexPath *selIndex;//单选,当前选中的行

然后在下面的代理方法实现代码

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //之前选中的,取消选择
    UITableViewCell *celled = [tableView cellForRowAtIndexPath:_selIndex];
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现tableview单选功能,可以通过以下步骤实现: 1. 在tableview的数据源中添加一个选中状态的属性,用来记录当前选中的cell。 2. 在tableview的代理方法中,处理cell的选中状态。可以通过设置cell的accessoryType或者accessoryView来实现不同的选中状态。 3. 在选中某个cell时,更新数据源中的选中状态,并重新加载tableview。 4. 在取消选中某个cell时,同样需要更新数据源中的选中状态,并重新加载tableview。 以下是一个简单的示例代码: ``` // 数据源中添加选中状态的属性 var selectedIndexPath: IndexPath? // 处理cell的选中状态 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "选项 \(indexPath.row)" if indexPath == selectedIndexPath { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } // 选中某个cell时更新选中状态 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndexPath = indexPath tableView.reloadData() } // 取消选中某个cell时更新选中状态 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { selectedIndexPath = nil tableView.reloadData() } ``` 在以上示例代码中,我们通过selectedIndexPath属性来记录当前选中的cell。在处理cell的选中状态时,如果该cell的indexPath与selectedIndexPath相同,则设置accessoryType为.checkmark,否则设置为.none。在选中某个cell时,将selectedIndexPath属性设置为该cell的indexPath,并重新加载tableview。在取消选中某个cell时,将selectedIndexPath属性设置为nil,并重新加载tableview

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值