如何设置它以便逐个下载图像并首先加载下载的图像?此外,当用户向下滚动同时清除或清除顶部的图像时,如何处理更多图像下载?
以下是我从Firebase异步下载这些图片的代码:
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("palettes").queryOrdered(byChild: "top").queryEqual(toValue: "#000000").observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let URL = each.value["URL"] as! String
if let url = NSURL(string: URL) {
if let data = NSData(contentsOf: url as URL){
let image = UIImage(data: data as Data)
self.imageArray.append(image!)
self.collectionView?.reloadData()
}
}
}
}
})
这是我填充collectionView的代码:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let textLabel = cell.viewWithTag(2)
let ootdImage = cell.viewWithTag(4) as! UIImageView
ootdImage.image = imageArray[indexPath.row]
textLabel?.backgroundColor = averageColor
return cell
}
编辑:现在,由于我的JSON树只包含三个条目,因此只下载了三个图像。但它们是完全下载的,因此我认为它必须是在所有三个图像下载并出现在同一时刻之前需要几秒钟的原因。
答案 0 :(得分:0)
func scrollViewDidScroll(scrollView: UIScrollView)
{
if scrollView.contentSize.height == scrollView.bounds.size.height + scrollView.bounds.origin.y {
//call web service here
}
}
还要在班级中添加UIScrollViewDelegate。
答案 1 :(得分:0)
我找到了解决方法:
使用alamofireImage,
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("palettes").queryOrdered(byChild: "top").queryEqual(toValue: "#000000").observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict as [String:AnyObject]{
let URL = each.value["URL"] as! String
self.URLArrayString.append(URL)
print(self.URLArrayString.count)
self.collectionView?.reloadData() //Reloads data after the number and all the URLs are fetched
}
}
})
获取所有URL和URL总数后,它将立即重新加载单元格(此时尚未下载图像,我们让alamofireImage逐个处理图像),这将我们带到下一个代码:< / p>
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let textLabel = cell.viewWithTag(2)
let ootdImage = cell.viewWithTag(4) as! UIImageView
// find out how to make it such that the data is gathered before being displayed.
//ootdImage.image = imageArray[indexPath.row]
let url = NSURL(string: URLArrayString[indexPath.row])
let placeholderImage = UIImage(named: "Rectangle")!
let filter = AspectScaledToFillSizeWithRoundedCornersFilter(
size: ootdImage.frame.size,
radius: 0
)
ootdImage.af_setImage(withURL: url as! URL, placeholderImage: placeholderImage, filter: filter, imageTransition: .crossDissolve(0.2)
)
textLabel?.backgroundColor = averageColor
return cell
}