Swift 3 UITableViewCell indexPath.row搞砸了
问题描述:
我有一个TableView来显示一堆电影。movies
是Movie对象的数组。 movieIDs
是电影ID的数组。 Ids只是字符串。Swift 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)
}
}
的在cellForRowAt方法循环:
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
在movieIDs
所有的ID比较影片的ID。如果它返回true,我替换单元格内的按钮的图像。当我在if语句内部打印时,它实际上不会执行,但它仍然替换随机单元格中的按钮图像。如果我上下滚动速度太快,几乎所有单元格中的按钮图像都会被替换,当它仅用于更改id匹配的单元格时。
答
的原因,这些细胞都塞因为它们是可重用的单元。例如,如果您将单元格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)
}
答
你必须设置nil
如果没有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
}