If 语句在 public 函数中不起作用? [Swift 3.0 - Xcode]

If Statements not working in public function? [Swift 3.0 - Xcode]

我试图通过附加条件来整理我的数据,因此我可以将其呈现在 table 中。我的条件是 AllData.count 必须等于 4。即使它等于 4,我的数据也不会附加到我的新数组中? 谁能告诉我怎么了?

var AllData = [String]()
var DataTable = [String]()

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    if AllData.count == 4 {
        DataTable.append(contentsOf: AllData)
        print("appended")
    }

    for i in stride(from: 0, to: DataTable.count - 1, by: 4) {
        cell.textLabel?.text = DataTable[i]
    }

    return cell
}

override func viewDidLoad(){
    print("AllData count ------->",AllData.count)
    print("Datatable count---------->",DataTable.count)
    super.viewDidLoad()
}

输出: 所有数据计数 ------> 4 数据table 计数------------> 0

首先,如果您在 table 视图中看不到任何内容,请检查是否在 viewDidLoad 中正确设置了委托和数据源。像这样

override func viewDidLoad(){
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

viewDidLoadcellForRowAt 之前完成。所以日志 AllData count -------> 4 Datatable count----------> 0 似乎是正确的。

但是,您的 cellForRowAt 出了点问题。你是说,如果 AllData 中有四个元素为真,则将 AllData 中的所有内容附加到 DataTable 中。然后循环遍历 DataTable 并为你的 UILabel 赋值?这样,您的标签将只包含来自 DataTable 最后一个元素的数据。此外,每次准备单元格时都会调用 cellForRow 。所以说对于第二个单元格,你 DataTable 将在 AllData 中有两次相同的数据,并且在你的循环中,你仍然将最后一个分配给标签。因此,无需更多代码,您将显示一个 table 视图,将在每个单元格上添加标签,显示 AllData 数组

中的最后一个元素

问题是 cellForRowAt:indexPath 仅在单元格 dequeued 时调用,因此您的逻辑仅在首次加载屏幕或滚动 [=12] 时触发=].相反,您想要做的是创建一个 func updateDataSource() ,每次 AllDataappended 时都会调用它。如果您更新 tableViewDataSource,您还必须在您的 for 循环中调用 tableView:insertRowAtIndexPath,这将向您的 tableView 添加新单元格。如果这不起作用,请致电 tableView.reloadData()