swift - 有没有一种更清洁的方法来部分填充 tableView
问题描述
我有一个带有两个标签和两个 UITextFields 的自定义单元格的 tableView,有时我的 tableView 会有 X 行,但我只需要填充前三个 UITextFields。
为了解决这个问题,我目前正在检查差异cellForRowAt
并像这样附加空字符串
if tableView.numberOfRows(inSection: 0) > someArray.count {
var difference = tableView.numberOfRows(inSection: 0) - someArray.count
while difference > 0 {
someArray.append("")
difference -= 1
}
虽然这行得通,但它感觉不是很优雅,并希望找到更好的方法。
感谢您的任何建议。
解决方案
如果索引大于或等于 someArray 的大小,最好的方法是将文本字段文本属性设置为“”:
cell.textField.text = indexPath.row < someArray.count ? someArray[indexPath.row] : ""
这就是我认为他们在评论中提出的建议。
看来您只是想清理代码,并有一种更简洁的方法来用默认值填充数组。我会这样使用Array.init(repeating repeatedValue: Element, count: Int)
:
let difference = tableView.numberOfRows(inSection: 0) - someArray.count
if difference > 0 {
someArray.append(contentsOf: Array(repeating:"", count: difference))
}
你可以变得非常可爱,并创建一个 Array 扩展来为你做这件事:
extension Array {
mutating func append(repeating repeatedValue: Element, count: Int) {
if count > 0 {
append(contentsOf: Array(repeating: repeatedValue, count: count))
}
}
}
然后:
someArray.append(repeating: "", count: tableView.numberOfRows(inSection: 0) - someArray.count)
推荐阅读
- sql - db2 表中的 join 语句
- python - Python 多维列表初始化 ...或纯 Python 等价于 numpy.zero
- snowflake-cloud-data-platform - 从 AWS S3 加载到 Snowflake 时从 ETC 转换为 UTC 时区
- javascript - Electron JS 高效地监视大量文件
- python - Glue ETL:如何使用 AWS 管理控制台将配置文件引用为额外文件?
- spring-boot - 使用 Spring Data 需要基于外键和 Order BY 值的不同记录
- javascript - 安装 webview2 后,Outlook 客户端中的 Office Web 插件卡在加载屏幕上,但在浏览器中运行良好
- git - azure devops git 错误:'致命:'testpr' 似乎不是 git 存储库,无法从远程读取。' 在 devops 中使用 git-request-pull 时
- java - 线程“主”java.lang.NoSuchMethodError 中的异常:执行 ServerBuilder.forPort(50051) 时
- android - 发送 Kotlin 挂起方法作为参数