我有一个UIScrollView,并使用UIPageControl来呈现图像。第一个图像出现的那一刻,程序崩溃并指示找到零值。
编辑:我不再为Scroll View下载图像,但我仍然收到错误。出现图像,然后程序崩溃。这是精简代码。在这一点上完全不知所措。仅供参考,我宣布变量i的原因是我打算循环并添加其他图像:
import UIKit
class HistoryViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
var frame = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 0, height: 0))
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.isPagingEnabled = true
let i = 0
frame.origin.x = self.scrollView.frame.size.width * CGFloat(i)
frame.size = self.scrollView.frame.size
let subView = UIImageView(frame: frame)
subView.image = UIImage(named: "maudite")
subView.contentMode = .scaleAspectFit
self.scrollView.addSubview(subView)
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(1), height: self.scrollView.frame.size.height)
}
}
.....................
我有两个理论为什么会这样。第一个是我添加到ScrollView的subView图像尚未加载。我正在使用AlamoFireImage,它以异步方式下载图像。 这是配置滚动视图的代码:
func configureScrollView() {
self.myScrollView.isPagingEnabled = true
for index in 0..<imageURLS.count {
frame.origin.x = self.myScrollView.frame.size.width * CGFloat(index)
frame.size = self.myScrollView.frame.size
let subView = UIImageView(frame: frame)
if let url = URL(string: imageURLS[index]) {
subView.af_setImage(withURL: (url))
subView.contentMode = .scaleAspectFit
self.myScrollView.addSubview(subView)
}
}
self.myScrollView.contentSize = CGSize(width: self.myScrollView.frame.size.width * CGFloat(imageURLS.count), height: self.myScrollView.frame.size.height)
pageControl.numberOfPages = imageURLS.count
}
可能导致问题的另一个原因是我首先要下载图片网址。我这样做并将它们存储在一个数组中。完成后,我调用configureScrollView()。我在主线程上进行调用。该函数是否在主线程上运行?
for dict in responseArray {
if let url = dict["fileName"] as? String {
let fullURL = "http://www.smarttapp.com" + url
print(fullURL)
self.imageURLS.append(fullURL)
}
}
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
self.networkingState = .finishedSearching
self.configureScrollView()
}
}