我正在尋找一種方法來平滑我的表格視圖。因為我有需要從 URL 下載影像的單元格,所以一個一個地加載 tableview 單元格非常慢并且會使 tableview 滯后。此外,每次回傳之前的單元格時,表格視圖都會重新加載。所以我希望我可以在加載時用影片分批加載 15 個單元格。關于我如何做到這一點的任何想法?任何幫助表示贊賞。
PS:我的下載功能合適嗎?還有其他更快更好的下載功能嗎?
我的代碼:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.row] // "post" are the firebase documents
if post.posttype == 1{
let cell = tableView.dequeueReusableCell(withIdentifier: TextPostCell.identifier, for: indexPath) as! TextPostCell
cell.titleText.text = post.title
cell.contentLable.text = post.content
cell.userPhoto.downloadImage(from: post.userphoto, placeHolder: UIImage(named: "notfound")!)
cell.username.text = post.sender
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: ImageTextPostCell.identifier, for: indexPath) as! ImageTextPostCell
cell.titleText.text = post.title
cell.photoImage.downloadImage(from: post.photo![0], placeHolder: UIImage(named: "notfound")!)
print("success")
cell.userphoto.downloadImage(from: post.userphoto, placeHolder: UIImage(named: "notfound")!)
cell.username.text = post.sender
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// tableview selected
}
extension UIImageView{
func downloadImage(from url: String?, placeHolder placeholder: UIImage) {
print("Download Started")
if let safeString = url{
if let safeURL = URL(string: safeString){
getData(from: safeURL) { data, response, error in
if error != nil{
print("Tony's Notes: Problem retrieving data")
print(error!)
self.image = placeholder
}
// always update the UI from the main thread
DispatchQueue.main.async() { [weak self] in
if let safeData = data{
self?.image = UIImage(data: safeData)
return
}
}
}
}else{
self.image = placeholder
}
}else{
self.image = placeholder
}
}
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
}
uj5u.com熱心網友回復:
您可能正在尋找預加載:預取行和預取消行。
https://developer.apple.com/documentation/uikit/uitableviewdatasourceprefetching
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515081.html
標籤:IOS迅速合适的视图
