如何返回循环的每个元素。我的意思是我希望将此循环的每个名称显示为行文本。它只返回最后一个元素。我该如何归还所有这些?
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
}
您不需要循环来显示UITableView
中的元素
假设你有一个姓氏数组:
var lastnames = ["....
并且您希望将每个元素放在UITableViewCell中。两个步骤:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lastnames.count
}
UITableView
:
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
}
只需更改您分配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
}
你最好创建一个元素数组arr []。用这个 :
cellFullname.textLabel?.text = arr[index.row]
更新:只需使用indexPath.row.
访问姓氏的每个元素
let cellFullname = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
cellFullname.textLabel?.text = lastnames[indexPath.row]
return cellFullname
}
如果你将在cellForRowAt
中添加for循环,那么每个单元格创建该循环将运行,这也不好。