0
我有cellForRowAt
方法獲取圖像並加載到單元格的imageView中的以下代碼。確認圖像是從打印語句下載的,但圖像未顯示在單元格中。請幫幫我。如何從UITableViewCell中的URL設置UIImageView的圖像?
let request = URLRequest(url: URL(string: imageURL)!)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {(data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded image with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
DispatchQueue.main.async {
cell.imgView.contentMode = .scaleAspectFit
cell.imgView.image = image
}
print("image received")
} else { print("Couldn't get image: Image is nil") }
} else { print("Couldn't get response code for some reason") }
}
}
dataTask.resume()
您是否在設置圖像時檢查'cell.imgView'是否不是'nil'? –
@SalmanGhumsani我想使用Apple提供的本地庫而不是AlamoFire。感謝您的迴應。 –
你有沒有在調試過程中瞭解'cell'的價值?和'cell.imgView'?他們有效嗎? – DonMag