gpt4 book ai didi

ios - 如何从 URL 按顺序而不是一起将图像加载到 imageView?

转载 作者:搜寻专家 更新时间:2023-11-01 07:21:13 26 4
gpt4 key购买 nike

<分区>

我正在尝试从 URL 将几张图片加载到我的 imageView 但我的代码设置方式是,应用程序会等待整组图片下载完毕,然后才会显示给用户的图像。一旦应用程序打开,这会导致大量等待时间。

要消除等待时间,图像必须从 webURL 下载后立即加载到 imageView,一张一张。有人可以建议如何执行此操作吗?

这是我的代码:

ViewController.swift

class ViewController: UIViewController , UICollectionViewDataSource {    

@IBOutlet weak var collectionView: UICollectionView!

let imageFetcher = ImageFetcher()

var counter = 0

override func viewDidLoad() {
super.viewDidLoad()

imageFetcher.setImageURL()
NSTimer.scheduledTimerWithTimeInterval(01, target: self, selector: #selector(addCells), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a nib.
}

func addCells(timer : NSTimer){

if(counter == imageFetcher.ImageArray.count){
timer.invalidate()
return
}

counter = counter + 1

let indexPath = NSIndexPath(forItem: counter-1 , inSection: 0)
collectionView.insertItemsAtIndexPaths([indexPath])
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("numberOfItemsInSection method just ran") //timeline indicator
return counter
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = imageFetcher.ImageArray[indexPath.row]
return cell
}
}

ImageFetcher.swift

class ImageFetcher {

var newImage : UIImage?
var ImageArray = [UIImage]()
var imageURL : NSURL?{
didSet{ newImage = nil
Adder()
}
}

func setImageURL(){
imageURL = DemoURLs.randomImageUrl
}

func fetchImage() {
if let url = imageURL{
let imageData = NSData(contentsOfURL: url)
if imageData != nil{
self.newImage = UIImage( data: imageData! )
} else {
self.newImage = nil

}
}
}

func Adder(){
for _ in 1...20 {

fetchImage()
ImageArray.append(newImage!)

}
}
}

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