簡體   English   中英

Swift 3 UITableViewCell indexPath.row搞砸了

[英]Swift 3 UITableViewCell indexPath.row messing up

我有一個TableView中顯示一堆的電影。 movies是電影對象的數組。 movieIDs是電影ID的數組。 id只是字符串。

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循環:

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)
        }

    }

我正在將movieIDs中的所有ID與該單元格處的電影ID進行比較,該電影是movie movies[indexPath.row].movieID 如果返回true,則替換單元格內按鈕的圖像。 當我在if語句中打印時,它實際上不會執行,但仍會替換隨機單元格上的按鈕圖像。 而且,如果我上下滾動太快,則按鈕的圖像將在幾乎所有單元格中被替換,而只是為了更改ID匹配的單元格而已。

填充單元格的原因是因為它們是可重復使用的單元格。

因此,例如,如果您為單元格1設置了圖像,則向下滾動時該單元格1離開屏幕並變為單元格10(例如),它仍在顯示圖像。

解決方案是您必須通過檢查先前設置的圖像是否與movieID不匹配來刪除該圖像,並將其設置為nil

您不必在這里進行for循環,而可以使用contains for數組。 因此,替換此代碼:

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)
}

如果沒有id匹配,則必須設置nil

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM