2017-05-19 41 views
-1

我想基於數組中的項目顯示tableview單元格,但由於一些奇怪的原因,它只會顯示數組中的第一個項目。當我使用打印語句時,它顯示正在迭代的數組。for循環只顯示數組中的第一項當試圖顯示在tableView

這裏是數組:

var restaurants = ["Truckyard", "EasySlider", "Revolver", "Armoury"] 

這裏是的cellForRowAtIndexPath:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = restaurantTableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! restaurantCell 

    for rest in restaurants { 

     cell.restaurantImageView.image = UIImage(named: rest) 
     cell.restaurantNameLabel.text = rest 

    } 

    return cell 
    } 
+0

你寫錯了。 您在單個單元格中有多少圖片視圖? –

+1

你不在'cellForRowAt'中使用'for'循環。這個函數每行調用一次。使用'indexPath.row'從數組中訪問正確的元素 – Paulw11

回答

2

cellForIndexPath爲每個行調用一次。試試這個:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = restaurantTableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! restaurantCell 

    cell.restaurantImageView.image = UIImage(named: restaurants[indexPath.row]) 
    cell.restaurantNameLabel.text = restaurants[indexPath.row] 

    return cell 
} 
0

不需要循環。 cellForRowAt爲您提供了一個indexPath。檢查indexPath.row屬性。如果您只有一個部分,則該行就是您要訪問的數組中的項目的索引。你基本上是遍歷每一行的數組,這將不可避免地將你的最後一項設置爲標題/圖像