ios - 对于 in,在 Swift 4 中需要时转到下一步

标签 ios swift

我正在使用 for in 制作大约 20 个单元格项目。

但是在for in 里面有DispatchQueue.main.async 并且for in 在它结束之前转到下一个。

所以我想在 DispatchQueue.main.async 完成后完成 for in。

这是代码:

for item in 0 ..< collectionView.numberOfItems(inSection: 0)
{
    let indexPath = IndexPath(item: item, section: 0)
    var photoHeight = CGFloat(50.0)

    _ = delegate.collectionView(collectionView, heightForPhotoAtIndexPath: indexPath)
    { (value) in
        DispatchQueue.main.async
            {
                photoHeight = value

                let height = self.cellPadding * 2 + photoHeight
                let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
                let insetFrame = frame.insetBy(dx: self.cellPadding, dy: self.cellPadding)

                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                attributes.frame = insetFrame
                self.cache.append(attributes)

                self.contentHeight = max(self.contentHeight, frame.maxY)
                yOffset[column] = yOffset[column] + height

                column = column < (self.numberOfColumns - 1) ? (column + 1) : 0
            }
    }

    // DispatchQueue.main.async is not finish, but it runs here.
}

最佳答案

您甚至不需要在这里使用 DispathQueue.main.async。你没有做任何 UI 工作,所以你不必在主线程上。

异步调用不会像您期望的那样按顺序运行。想想网络电话..

print('starting network call')

NetworkClient.get(url) { response, error in 
    print('returned from network')
}

print('function complete')

如果你调用它,可能的输出是:

starting network call

function complete

returned from network

这是因为异步函数被分派(dispatch)并且需要时间才能完成,但是执行可以继续进行。网络调用完成后,回调/完成处理程序将被调用,然后该代码将运行。

Here is another example Swift 中的异步函数调用

关于ios - 对于 in,在 Swift 4 中需要时转到下一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53041027/

相关文章:

ios - UiView setFrame 对象

ios - 二维码扫描后内存峰值/泄漏

html - iOS 删除除 <p> 之外的所有 HTML 标签

ios - UIKit-Swift 自定义 UIButton 不会触发点击 Action

ios - 如何符合 MutableCollection?

iphone - 在FBConnect ios中通过graph api获取page_access_token

iOS 应用程序打开后立即崩溃

ios - 修改 UITextView 的框架使其看起来像一个对话泡泡

iOS核心图像过滤器参数

ios - 如何在不不断查询后端的情况下刷新 UI 标签?