执行 segue 时,主线程上的 UI 未更新



我正在尝试通过执行/准备 segue 将图像添加到位于另一个视图控制器中的另一个 imageView.image,但是当我尝试在 bg 线程中执行变量然后跳到主线程进行更新时,它不起作用。但是如果我删除调度的东西,那么它就可以了。代码如下:

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    SwiftSpinner.show(progress: 0.2, title: "Loading full image, please wait...")
    let vc = segue.destination as! PhotoViewController
    let cell = sender as! UICollectionViewCell
    DispatchQueue.global(qos: .background).async {
        if let indexPath = self.collectionView?.indexPath(for: cell) {
            let url = URL(string: self.images[indexPath.row].rawURL)
            let imageData = NSData(contentsOf: url!)
            let image = UIImage(data: imageData as! Data)
            DispatchQueue.main.async {
                vc.image = image!
                vc.mainImage = image!
                vc.photographerName = self.images[(indexPath.row)].photographerName
                SwiftSpinner.hide()
            }
        }
    }
}

我会推荐KingFisher做这样的事情。它把所有的垃圾都变成:

 . . .
let cell = sender as! UICollectionViewCell
let url = URL(string: self.images[indexPath.row].rawURL)
vc.imageView.kf.setImage(with: url)
 . . .

但是,是的。@dlbuckley是对的。如果你不做像KingFisher这样的事情,就不要在准备ForSegue时做这些事情。

最新更新