如何获取UITableViewCell内置accessoryType的尺寸及内边距?
获取UITableView内置Accessory的尺寸与内边距(未渲染时)
这个问题我之前也碰到过,在cell还没渲染的时候,直接拿内置accessory的尺寸和间距确实有点棘手,不过有个靠谱的解决思路:创建一个同类型的临时单元格,模拟目标cell的配置(比如设置对应的accessoryType),再通过触发布局来获取准确的参数——因为系统内置的accessory是标准组件,临时cell的计算结果和实际渲染的cell完全一致,而且临时cell不会被添加到视图层级,对性能没影响。
具体实现步骤:
初始化临时cell
根据你实际使用的cell类型创建临时实例,同时设置好对应的accessoryType(.checkmark或.disclosureIndicator),并把它的宽度设为当前tableView的宽度,保证布局和实际cell一致。触发布局计算
调用layoutIfNeeded()让临时cell完成布局,这样才能拿到准确的frame值。获取所需参数
- 内置accessory的宽高:直接从临时cell的
accessoryView中获取bounds.size - contentView与accessory的间距:通过tableView宽度减去contentView宽度、再减去accessory宽度的差值计算得到(这个差值包含了accessory和contentView之间的间距,以及accessory到cell右边缘的间距)
- 内置accessory的宽高:直接从临时cell的
示例代码(放在tableView(_:heightForRowAt:)方法中)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // 假设根据业务条件判断要使用的accessoryType let useCheckmark = someConditionForIndexPath(indexPath) let targetAccessoryType: UITableViewCell.AccessoryType = useCheckmark ? .checkmark : .disclosureIndicator // 创建临时cell(替换成你自己的cell类) let tempCell = YourCustomCell(style: .default, reuseIdentifier: nil) tempCell.accessoryType = targetAccessoryType // 设置临时cell宽度为tableView的宽度,保证布局和实际一致 let tableViewWidth = tableView.bounds.width tempCell.frame = CGRect(x: 0, y: 0, width: tableViewWidth, height: UITableView.automaticDimension) // 触发布局计算 tempCell.layoutIfNeeded() // 获取accessory的宽高 let accessoryWidth = tempCell.accessoryView?.bounds.width ?? 0 let accessoryHeight = tempCell.accessoryView?.bounds.height ?? 0 // 获取contentView和accessory之间的总间距(含accessory到cell右边缘的距离) let contentToAccessorySpacing = tableViewWidth - tempCell.contentView.bounds.width - accessoryWidth // 现在可以用contentView的宽度计算子视图的精确宽度了 // 比如你的子视图有左右各16的内边距: let subViewAvailableWidth = tempCell.contentView.bounds.width - 16 * 2 // 后续根据子视图宽度计算cell高度... return calculatedCellHeight }
额外优化建议
如果你的列表中只有两种accessoryType,可以把计算出来的accessoryWidth和contentToAccessorySpacing缓存起来,不用每次调用heightForRowAt都创建临时cell,能提升一点性能。
内容的提问来源于stack exchange,提问作者Ahmed Khedr
相关产品推荐
相关产品推荐

