如何将循环的每个元素显示到表行?

问题描述 投票:1回答:4

如何返回循环的每个元素。我的意思是我希望将此循环的每个名称显示为行文本。它只返回最后一个元素。我该如何归还所有这些?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)

        for last in lastnames {
            cellFullname.textLabel?.text = "\(last)"
        }
        return cellFullname
    }
ios swift uitableview loops
4个回答
2
投票

您不需要循环来显示UITableView中的元素

假设你有一个姓氏数组:

var lastnames = ["....

并且您希望将每个元素放在UITableViewCell中。两个步骤:

  1. 定义所需的细胞数量: override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lastnames.count }
  2. 使用以下名称更新UITableViewfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) cellFullname.textLabel?.text = lastnames[indexPath.row] return cellFullname }

2
投票

只需更改您分配textLabel.text的部分:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)


    cellFullname.textLabel?.text = lastnames[indexPath.row]

    return cellFullname
}

0
投票

你最好创建一个元素数组arr []。用这个 :

cellFullname.textLabel?.text = arr[index.row]

0
投票

更新:只需使用indexPath.row.访问姓氏的每个元素

    let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)

    cellFullname.textLabel?.text = lastnames[indexPath.row]

    return cellFullname
}

如果你将在cellForRowAt中添加for循环,那么每个单元格创建该循环将运行,这也不好。

© www.soinside.com 2019 - 2024. All rights reserved.