2017-03-07 11 views
0

나는 영화를 잔뜩 보여주기 위해 TableView를 가지고있다. movies은 영화 객체의 배열이다. movieIDs은 영화 ID 배열입니다. ID는 단지 문자열입니다. cellForRowAt 방법에 루프스위프트 3 UITableViewCell indexPath.row 엉망진창

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as! MovieCell 

     // editing the cell here. 

     cell.movieNameLabel.text = movies[indexPath.row].movieName 
     cell.movieYearLabel.text = movies[indexPath.row].year 

     // source of all hell here. 

     for id in movieIDs { 

      if id == movies[indexPath.row].movieID { 

       print(id + " is equal to " + movies[indexPath.row].movieID) 
       cell.myButton.setImage(/*there is an image here*/), for: .normal) 

      } 

     } 

: 나는 movies[indexPath.row].movieID 인 셀에서 영화의 ID로 movieIDs의 모든 ID를 비교하고

for id in movieIDs { 

     if id == movies[indexPath.row].movieID { 

      print(id + " is equal to " + movies[indexPath.row].movieID) 
      cell.myButton.setImage(//there is an image here), for: .normal) 
     } 

    } 

. true를 반환하면 셀 안의 버튼 이미지를 바꿉니다. if 문 내부에서 인쇄 할 때 실제로 실행되지는 않지만 임의의 셀에서 버튼 이미지를 대체합니다. 그리고 너무 빨리 위아래로 스크롤하면 단추의 이미지가 거의 모든 셀에서 바뀝니다. 단, id가 일치하는 셀만 변경하면됩니다. 더 나은 솔루션에 대한

var matched = false 
for id in movieIDs { 

    if id == movies[indexPath.row].movieID { 

     print(id + " is equal to " + movies[indexPath.row].movieID) 
     cell.myButton.setImage(//there is an image here), for: .normal) 
     matched = true 
    } 

} 

if !matched { 
    cell.myButton.setImage(nil) 
} 

, 당신은 함수를 작성해서는 안 이미지를 얻을 : 세포가 박제되어

if let image = getMovieImageByID(movies[indexPath.row].movieID) { 
    cell.myButton.setImage(image), for: .normal) 
} else { 
    cell.myButton.setImage(nil), for: .normal) 
} 

func getMovieImageByID(movieID: String) -> UIImage? { 
    for id in movieIDs { 
     if id == movieID { 
      // return the image for the respective movieID 
     } 
    } 

    return nil 
} 

답변

2

이유를

0

당신은 더 id 일치하는 경우 nil을 설정해야 그들이 재사용 할 수있는 세포이기 때문입니다.

예를 들어, 셀 # 1에 이미지가 설정되어 있고 아래로 스크롤하여 셀 # 1이 화면에서 벗어나서 셀 # 10 (예 :)이되면 이미지가 계속 표시됩니다.

해결책은 movieID과 일치하지 않는지 확인하여 이전에 설정 한 이미지를 제거해야하며 이미지를 nil으로 설정해야합니다.

여기서 for 루프를 수행 할 필요없이 어레이에 contains을 사용하십시오. 이와

for id in movieIDs { 

    if id == movies[indexPath.row].movieID { 

     print(id + " is equal to " + movies[indexPath.row].movieID) 
     cell.myButton.setImage(//there is an image here), for: .normal) 
    } 

} 

:

if movieIDs.contains(movies[indexPath.row].movieID) { 
    cell.myButton.setImage(//there is an image here), for: .normal) 
} 
else{ 
    cell.myButton.setImage(nil) 
} 
그래서이 코드를 교체