ios - 在 Swift 4 中,当我想要时转到下一个
<p><p>我正在使用 for in 制作大约 20 个单元格项目。</p>
<p>但是在 for in 中有 DispatchQueue.main.async 并且 for in 在它结束之前进入下一个。</p>
<p>所以我想在 DispatchQueue.main.async 完成后完成。</p>
<p>这是代码:</p>
<pre><code>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, y: yOffset, 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 = yOffset + height
column = column < (self.numberOfColumns - 1) ? (column + 1) : 0
}
}
// DispatchQueue.main.async is not finish, but it runs here.
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你甚至不需要在这里使用 <code>DispathQueue.main.async</code>。你没有做任何 UI 工作,所以你不必在主线程上。</p>
<p>异步调用不会像您期望的那样按顺序运行。想想网络调用..</p>
<pre><code>print('starting network call')
NetworkClient.get(url) { response, error in
print('returned from network')
}
print('function complete')
</code></pre>
<p>如果你这样调用它,可能的输出是:</p>
<blockquote>
<p>starting network call</p>
<p>function complete</p>
<p>returned from network</p>
</blockquote>
<p>这是因为异步函数被调度并需要时间来完成,但在此过程中执行可以继续。一旦网络调用完成,回调/完成处理程序将被调用,然后该代码将运行。</p>
<p> <a href="https://stackoverflow.com/questions/33476778/returning-data-after-async-task" rel="noreferrer noopener nofollow">Here is another example</a> Swift 中的异步函数调用次数</p></p>
<p style="font-size: 20px;">关于ios - 在 Swift 4 中,当我想要时转到下一个,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/53041027/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/53041027/
</a>
</p>
页:
[1]