iOS 的 UITableview 和可变单元格高度

问题描述 投票:0回答:1

我正在使用 UITableview 实现提要,其中图像加载到每个单元格中(全宽)

由于每个单元格的每个图像都有不同的大小(和长宽比),我想从 url 加载相应的图像,并将图像放入单元格内的 UIImageView 中,调整单元格大小以适应图像的长宽比。

如何异步调整单元格的高度? (也就是说,不是在创建单元格时,而是在从网络加载图像时)

谢谢

ios swift uitableview
1个回答
0
投票

这只是一个解决方案:

您可以获得所有网址的尺寸,在获得所有尺寸后,您可以根据您的用户体验加载表格视图:

您可以从 Queuer 使用:https://github.com/FabrizioBrancati/Queuer

import Queuer

let queue = Queuer(name: "MyQueue",
                   maxConcurrentOperationCount: 1000,
                   qualityOfService: .default)

还有这个功能

let cellupdate = NSNotification.Name("cellupdate")
func imageDimenssions(url: String, index: Int) {
    let concurrentOperation = ConcurrentOperation { _ in
        if let imageSource = CGImageSourceCreateWithURL(URL(string: url)! as CFURL, nil) {
            if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {
                let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as? Int ?? 0
                let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as? Int ?? 0
                
// update "yourItems" list with index and width and height with index and update your list with index(width and height)
                let userInfo = "index": index, "width": pixelWidth, "height": pixelHeight]
                NotificationCenter.default.post(name: cellupdate,
                                                object: nil,
                                                userInfo: userInfo)
            }
        }
    }
    queue.addOperation(concurrentOperation)
    queue.waitUntilAllOperationsAreFinished()
    queue.addCompletionHandler {
        DispatchQueue.main.async {
//            reload table view
        }
    }
}

在 viewdidload() 等函数中调用此循环

for (item, index) in yourItems.enumerated() {
     imageDimenssions(url: item.url, index: index)
}

之后你应该计算你想要的图像的高度, 例如,如果图像宽度固定为屏幕尺寸减去 32 像素(16 个尾部 + 16 个前导)

你可以用这个解决方案来计算

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let width = yourItems[indexPath.row].width
        let height = yourItems[indexPath.row].height
        return (screenWidth - 32) * height / width
    }
© www.soinside.com 2019 - 2024. All rights reserved.