首页 > 解决方案 > 有没有一种更清洁的方法来部分填充 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
                }

虽然这行得通,但它感觉不是很优雅,并希望找到更好的方法。

感谢您的任何建议。

标签: swiftuitableview

解决方案


如果索引大于或等于 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)

推荐阅读