[英]Swift - Dynamic UITableViewCell size based on image aspect ratio
我正在嘗試創建動態大小的UITableViewCells,根據從服務器下載的圖像的寬高比來改變高度。
例如,如果圖像的高度是其寬度的兩倍,我希望UITableViewCell的高度是屏幕寬度的兩倍,這樣圖像就可以占據屏幕的整個寬度並保持縱橫比。
我試圖做的是添加約束到單元格並使用UITableViewAutomaticDimension來計算高度,但我面臨的問題是我無法知道圖像的寬高比,直到下載,因此單元格開始小,然后手動刷新tableView后,單元格顯示正確的大小。
我不想在下載圖像時重新加載每個單元格也是一種很好的方法。
這種方法是最好的方法嗎? 我不能為我的生活思考如何做到這一點,因為我在初始化時無法從細胞內部知道縱橫比。
為了達到這個目的,我首先使用字典[Int:CGFloat]
來保持計算出的單元格高度然后在heightForRowAtIndexpath
方法中使用keeped在你的字典中,在你的cellForRowAtIndexpath
方法中你應該下載你的圖像,計算寬高比,乘以你的按寬高比划分單元格寬度或圖像寬度,並將相應的IndexPath編號中的高度計算在字典中
在類似這樣的代碼中,這是使用alamofire加載圖像的代碼示例
var rowHeights:[Int:CGFloat] = [:] //declaration of Dictionary
//My heightForRowAtIndexPath method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = self.rowHeights[indexPath.row]{
return height
}else{
return defaultHeight
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as? ImageCell
{
let urlImage = Foundation.URL(string: "http://imageurl")
cell.articleImage.af_setImage(withURL: urlImage, placeholderImage: self.placeholderImage, filter: nil, imageTransition: .crossDissolve(0.3), completion: { (response) in
if let image = response.result.value{
DispatchQueue.main.async {
let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width
cell.articleImage.image = image
let imageHeight = self.view.frame.width*aspectRatio
tableView.beginUpdates()
self.rowHeights[indexPath.row] = imageHeight
tableView.endUpdates()
}
}
})
}
我希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.