在 iOS 应用程序中实现类似单选按钮的行为
💡一则或许对你有用的小广告
欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论
- 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于
Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...
,点击查看项目介绍 ;- 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;
截止目前, 星球 内专栏累计输出 82w+ 字,讲解图 3441+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2800+ 小伙伴加入学习 ,欢迎点击围观
我一直觉得 iOS 开发有点令人沮丧的一件事是缺少选择控件,如单选按钮和下拉列表。这些控件在其他平台上无处不在,大多数用户对其使用和行为感到满意。
幸运的是,可以使用
UITableView
来模拟这些控件的行为。
Apple 建议
使用复选标记来表示选择状态;然而,这不是免费的——它必须由应用程序为每个需要它的表视图或表视图部分实现。
因为它是一个如此常见的隐喻,
MarkupKit
的
LMTableView
类现在支持自动实现类似单选按钮的行为。将
LMTableView
中任何部分的选择模式设置为“singleCheckmark”可确保在任何给定时间仅选中一行。 MarkupKit 将布尔
checked
属性添加到
UITableViewCell
类,以允许应用程序获取或设置单元格的选择状态。
例如,以下标记创建了一个表视图,允许用户从尺寸选项列表中选择一个值。默认选中“大”选项:
<LMTableView style="groupedTableView">
<?sectionSelectionMode singleCheckmark?>
<UITableViewCell textLabel.text="Small"/>
<UITableViewCell textLabel.text="Medium"/>
<UITableViewCell textLabel.text="Large" checked="true"/>
<UITableViewCell textLabel.text="Extra-Large"/>
</LMTableView>
此标记生成类似于以下内容的输出:
下面的 Swift 代码产生了相同的结果,尽管有点冗长:
<LMTableView style="groupedTableView">
<?sectionSelectionMode singleCheckmark?>
<UITableViewCell textLabel.text="Small"/>
<UITableViewCell textLabel.text="Medium"/>
<UITableViewCell textLabel.text="Large" checked="true"/>
<UITableViewCell textLabel.text="Extra-Large"/>
</LMTableView>
将一个部分的选择模式设置为“multipleCheckmarks”可以启用类似于其他平台上的复选框集合的选择行为。例如,以下标记创建了一个宠物选择列表,用户可以从中选择零个或多个值。默认选中“Cat”和“Turtle”:
<LMTableView style="groupedTableView">
<?sectionSelectionMode singleCheckmark?>
<UITableViewCell textLabel.text="Small"/>
<UITableViewCell textLabel.text="Medium"/>
<UITableViewCell textLabel.text="Large" checked="true"/>
<UITableViewCell textLabel.text="Extra-Large"/>
</LMTableView>
此标记生成类似于以下内容的输出:
MarkupKit 还向
UITableViewCell
添加了一个
value
属性,允许应用程序将可选值与单元格相关联,类似于 HTML
<select>
元素中
<option>
的“value”属性。例如,以下标记创建了一个表视图,允许用户选择颜色。表格视图的控制器通过将所选单元格的值应用为另一个单元格的背景颜色来响应选择更改:
<LMTableView style="groupedTableView">
<?sectionSelectionMode singleCheckmark?>
<UITableViewCell textLabel.text="Small"/>
<UITableViewCell textLabel.text="Medium"/>
<UITableViewCell textLabel.text="Large" checked="true"/>
<UITableViewCell textLabel.text="Extra-Large"/>
</LMTableView>
相关控制器代码如下:
<LMTableView style="groupedTableView">
<?sectionSelectionMode singleCheckmark?>
<UITableViewCell textLabel.text="Small"/>
<UITableViewCell textLabel.text="Medium"/>
<UITableViewCell textLabel.text="Large" checked="true"/>
<UITableViewCell textLabel.text="Extra-Large"/>
</LMTableView>
结果输出:
LMTableView
的这些新选择管理功能使得处理 iOS 应用程序设计中的一些常见使用场景变得更加容易。