2017-05-19 3 views
-1

배열의 항목을 기반으로 tableview 셀을 표시하려고하지만 일부 이상한 이유로 배열의 첫 번째 항목 만 표시합니다. print 문을 사용할 때 올바르게 반복되는 배열을 보여줍니다.for 루프는 tableView에 표시하려고 할 때 배열의 첫 번째 항목 만 표시합니다.

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 행마다 한번 호출된다 : 여기

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 

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

    return cell 
} 
0

루프가 필요 없습니다. cellForRowAt가 indexPath를 제공합니다. indexPath.row 속성을 확인하십시오. 섹션이 하나만있는 경우 행은 액세스하려는 어레이의 항목 색인입니다. 기본적으로 각 행에 대해 배열을 반복하므로 제목/이미지로 마지막 항목을 필연적으로 설정합니다.

관련 문제