2016-11-22 39 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循環,然後爲每個單元創建循環將運行,這也不好。

相關問題