2016-11-22 43 views
0

如何返回循环的每个元素。我的意思是我想要显示这个循环的每个名字来行文本。它只是返回最后一个元素。我怎样才能返回所有这一切?
如何将循环的每个元素显示到表格行?

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 
    } 
+1

移除循环做这样的名字[ indexpath.row] – seggy

回答

1

你并不需要一个循环为UITableView

显示元素假设你有一个姓氏的数组:

var lastnames = [".... 

而且你希望把每一个元素在一个UITableViewCell。两个步骤:

  1. 定义单元格的你所需要的量:

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return lastnames.count 
    } 
    
  2. 更新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 
    } 
    
0

您最好创建一个元素数组arr []。 使用此:

cellFullname.textLabel?.text = arr[index.row] 
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

更新时间: 使用indexPath.row.

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

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

    return cellFullname 
} 

如果你刚刚接触lastnames的每个元素将为cellForRowAt添加for循环,然后为每个单元创建循环将运行,这也不好。

相关问题