惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
U
Unit 42
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
美团技术团队
雷峰网
雷峰网
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
D
DataBreaches.Net
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
罗磊的独立博客
MyScale Blog
MyScale Blog
博客园_首页
IT之家
IT之家
F
Fortinet All Blogs
博客园 - Franky

Oragekk's Blog

A2UI:当 AI Agent 开始直接生成界面 OpenSpec 技术分享:用规格驱动 AI 编程 ChatGPT&Codex订阅教程 一个 waline 评论系统bug引发的思考 Jenkins 远程触发构建踩坑记 Git SSH 密钥配置 初识Rust vuepress-plugin-meting2 谷歌发布多平台应用开发神器Project IDX!PaLM 2加持 Vue常见优化手段 Vue2响应式原理解析 Dart 中的并发 Flutter 工作原理 如何利用GitHub Action提交URL到搜索引擎 提交URL到搜索引擎(百度、Bing、Google) GitHub Actions 使用介绍 素材设计 前端-Q&A 浏览器的事件循环 你不知道的 CSS 之包含块 CSS 属性计算过程 Vercel deploy忽略指定分支 评论插件 Waline 之邮件通知配置 公开API 终端究极美化iTerm2+Pure 使用Bing API提交网站URL Flutter 基础大集合 关于本站 关于本站 关于我
优雅的实现TableViewCell单选
Oragekk · 2018-01-12 · via Oragekk's Blog

最近有些忙,好久没有写博客了。
分享一个 cell 做单选的思路

可行的思路

  1. 在 tableview 的控制器中设立一个变量记录选择的 indexPath,点击 cell 之后刷新表格来和现有 indexPath 对比
  2. 和第一种大同小异,做一个和 dataArr 同样的数组,记录 indexPath,循环确定当前 cell 是否为选中 cell
  3. 利用 cell 的- (void)setSelected:(BOOL)selected animated:(BOOL)animated方法

利弊分析

  1. 前两种,都需要在didSelectRowAtIndexPath方法中来刷新表格,可能会造成不必要的滑动,而且需要单独的外在属性来记录这个选择
  2. 第三种方法是我要介绍的,不用任何外在属性,不用变量,不用数组。实现 cell、或 cell 中 Button 的单选。并且不会因为复用而造成位置错乱,如果要实现 cell 的多选可以参考我之前的文章Cell 的 accessoryType 属性标记单元格之后,出现的重用问题

实现方式

  1. 如果要有默认选择在初始化 tableView 完成后写

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
  2. 然后在 cell 中实现- (void)setSelected:(BOOL)selected animated:(BOOL)animated方法

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    	if (selected) {
        	self.selBtn.selected = YES;
    	}else {
        	self.selBtn.selected = NO;
    	}
    }
  3. didSelectRowAtIndexPath方法中给点击的 cell 手动选中,并不需要刷新表格

    [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

至此结束,可以看一下效果
效果图.md.gif