所以我在循环中向 ViewController 的 View 添加了几个 subview ;问题是从我添加 subview 开始,它的显示有大约 5 秒的延迟。 我确保在添加 subview 和我的 View 后调用 setNeedsDisplay,没有骰子。我什至使用 NSThread.isMainThread()
仔细检查了代码正在在主线程上执行,并且它按预期返回了 true。这是我的确切代码:
dispatch_async(dispatch_get_main_queue()) {
var nib = UINib(nibName: "ProfileCard", bundle: NSBundle.mainBundle())
var profiles = self.delegate.user!.profilesToShow
//loop to add ProfileCard subviews
while profiles.count > 0 && self.deck.count < self.MAX_DECK_SIZE {
println("Adding Card")
//setup subview
var card = nib.instantiateWithOwner(self, options: nil).first! as ProfileCard
card.delegate = self
card.frame = CGRect(x: (self.view.bounds.width - 300)/2, y: 100, width: 300, height: 200)
card.displayProfile(profiles.first!)
//add subview
self.view.addSubview(card)
self.view.sendSubviewToBack(card)
card.setNeedsDisplay()
self.view.setNeedsDisplay()
//add card to deck, mark as shown
self.deck.append(card)
profiles.removeAtIndex(0)
}
}
此循环中的任何打印语句在 subview 实际显示之前运行约 5 秒,我不确定这是由于什么原因造成的。我什至在 subview 的init方法中设置了打印语句,甚至打印了预期的。
最佳答案
此代码可能不在后台线程上运行,但您必须进入主线程的事实表明您有其他 正在在后台线程上运行的代码。其他代码是问题的根源。它正在尝试与后台线程上的界面对话。这反过来又破坏了整个绘图系统。
关于ios - Swift/iOS subview 在主线程上不立即显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27699471/