我正在尝试从服务器下载图像并想在我的单元格中加载图像,但是当我在 cellForRowAt 方法中下载时,它不会第一次获得高度。如果我向上滚动并再次向下滚动,图像将具有适当的高度。
使用 Kingfisher 从服务器下载图像
var homeList = [NSDictionary]()
var rowHeights : [Int:CGFloat] = [:]
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homeList.count
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = self.rowHeights[indexPath.row]{
print(" Height \(height)")
return height
}
else{
return 160
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let homeObject = homeList[safe: indexPath.row] {
if let dynamicURL = homeObject["dynamic_card_url"] as? String, dynamicURL != "" {
tableView.register(UINib(nibName: "DynamicCell", bundle: nil), forCellReuseIdentifier: "\(indexPath.row)")
let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.row)", for: indexPath) as! DynamicCell
KingfisherManager.shared.downloader.downloadImage(with: URL(string: dynamicURL)!, options: .none, progressBlock: nil, completionHandler: { (image, error, url, data) in
DispatchQueue.main.async {
if (image != nil || url != nil){
let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width
cell.dynamicImageView.image = image
let imageHeight = self.view.frame.width*aspectRatio
self.rowHeights[indexPath.row] = imageHeight
}else{
print("Image or URL is nil")
}
}
})
cell.selectionStyle = .none
cell.backgroundColor = UIColor.clear
return cell
}
}
}