gpt4 book ai didi

ios - Collection View 加载不稳定

转载 作者:行者123 更新时间:2023-11-28 06:55:01 27 4
gpt4 key购买 nike

我有一个从 API 加载数据的 Collection View 。 Collection View 工作正常,除了它只在滚动时加载图像。我试过异步加载图像,但差别很小。我想要加载所有图像或在图像加载之前预加载图像?我正在使用 Haneke 从 URL 加载图像。这是我在 Collection View 中使用的代码:

  func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.tableData.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: ProductsViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("productViewCell", forIndexPath: indexPath) as! ProductsViewCell

let rowData = tableData[indexPath.row]

cell.backgroundColor = UIColor.whiteColor()

for (key,value) in rowData {
cell.productPrice.text = value["merged"][0]["variants"][0]["price"].string
cell.productName.text = value["merged"][0]["title"].string


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if let imageString = value["merged"][0]["images"][0]["src"].string {
let url = NSURL(string: imageString)

dispatch_async(dispatch_get_main_queue(), {
cell.productImage.contentMode = .ScaleAspectFill
cell.productImage.hnk_setImageFromURL(url!)
})
}
})


if let variantData = value["merged"][0]["variants"].array {
var sum = 0

for variant in variantData {
sum += variant["inventory_quantity"].int!
}

if sum <= 0 {
cell.soldOut.hidden = false

} else {
cell.soldOut.hidden = true
}
}


}

return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("Cell \(indexPath.row) selected")
}

最佳答案

您想要完成主线程的所有下载,然后在图像或图像数据可用时分派(dispatch)到主队列以更新 UI。在这里,您的方向是正确的,但您是在主线程上下载。改变这个:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if let imageString = value["merged"][0]["images"][0]["src"].string {
let url = NSURL(string: imageString)

dispatch_async(dispatch_get_main_queue(), {
cell.productImage.contentMode = .ScaleAspectFill
cell.productImage.hnk_setImageFromURL(url!)
})
}
})

收件人:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if let imageString = value["merged"][0]["images"][0]["src"].string {
let url = NSURL(string: imageString)
let imageData = NSData(contentsOfURL: imageString)
let image = UIImage(data: imageData)

dispatch_async(dispatch_get_main_queue(), {
cell.productImage.contentMode = .ScaleAspectFill
cell.productImage.image = image
})
}
})

关于ios - Collection View 加载不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882815/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com