【发布时间】:2020-10-12 07:59:16
【问题描述】:
我正在下载几张图片并缓存它们。然后我正在调用缓存的图像并将它们作为子视图添加到我的滚动视图(使用页面控制器是水平的)。当视图出现而不需要任何其他操作时,我想同时执行这两项操作。不幸的是,它已经在图像被缓存之前添加了子视图,因为它在下载图像时会遍历代码。因此没有添加任何内容作为子视图。
当我在视图出现时下载和缓存图像并在按下按钮时将它们添加为子视图时,它可以工作,但我希望它能够自动工作。
我不确定我的代码是否有助于更好地理解,但确实如此。
这是我下载图片的代码
func downloadImage(url: URL) {
let dataTask = URLSession.shared.dataTask(with: url) { data, responseURL, error in
var downloadedImage:UIImage?
if let data = data {
downloadedImage = UIImage(data: data)
}
// if download actaully got an image
if downloadedImage != nil {
self.sum += 1
self.cache.setObject(downloadedImage!, forKey: url.absoluteString as NSString) // cache the image
// add the url as value to the dictionary
self.imageURLS[self.sum] = url.absoluteString
}
}
dataTask.resume()
}
这就是我用来添加子视图的方法
func appendImages(){
// sort the values of the dictionary by the greatest
let sortedImageURLs = Array(imageURLS.keys).sorted(by: >)
var stringURLs = [String]() // empty string array to append the URL's
// for loop which goes through all integers in "creation Date" array
for keys in sortedImageURLs {
let url: String? = imageURLS[keys] // url which is connected to the key
stringURLs.append(url!) // append the url to the url array
}
// -> the url string array starts with the latest loaded url
var originSubview = 0 // counter of the origin of the subviews
for urls in stringURLs {
// 1.
frame.origin.x = scrollView.frame.size.width * CGFloat(originSubview)
frame.size = scrollView.frame.size
// 2.
let imageView = UIImageView(frame: frame)
// get the image which is cahed under the url
let image = cache.object(forKey: urls as NSString)
// set the image of image view as the cached image
imageView.image = image
// and add that image view as a subview to the scrollView
scrollView.addSubview(imageView)
// increase counter variable by one
//-> next images origin is at the end of the image before
originSubview += 1
}
// 3.
scrollView.contentSize = CGSize(width: ((scrollView.frame.size.width) * CGFloat(specialsCounter)), height: (scrollView.frame.size.height))
scrollView.delegate = self
pageControl.numberOfPages = specialsCounter
}
【问题讨论】:
-
你在哪里调用
downloadImage函数 -
到目前为止的视图中会出现
标签: ios swift download addsubview