简体   繁体   English

Swift / iOS子视图未立即显示在主线程上

[英]Swift/iOS Subview Not Showing Immediately, on Main Thread

So I'm adding several subviews to my ViewController's view in a loop; 因此,我要在循环中向ViewController的视图中添加几个子视图; the problem is there's a ~5s delay for it in showing up from the time I add the subview. 问题是,从我添加子视图开始,它的显示会延迟约5秒钟。 I made sure to call setNeedsDisplay on both the subview and my view after adding it, no dice. 添加后, 确保在子视图和视图上都调用setNeedsDisplay ,没有骰子。 I even double-checked that the code is executing on the main thread using NSThread.isMainThread() , and it returned true as expected. 我什至使用NSThread.isMainThread()再次检查了代码是否在主线程上执行 ,并且按预期返回了true。 Here's my exact code: 这是我的确切代码:

    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)
        }
    }

Any print statements in this loop run about ~5s prior to the subview actually displaying, and I'm not sure what that's due to. 此循环中的所有打印语句在实际显示子视图之前大约运行5秒钟,我不确定这是什么原因。 I even set print statements in the init method of the subview, and even those printed with expected. 我什至在子视图的init方法中设置了打印语句,甚至是按预期打印的语句。

This code may not be running on a background thread, but the fact that you have to come onto the main thread suggests that you have other code that is running on a background thread. 代码不能在后台线程上运行,但事实上,你必须要他到主线程建议有在后台线程上运行其他代码。 That other code is the source of the problem. 该其他代码是问题的根源。 It is trying to talk to the interface on the background thread. 它正在尝试与后台线程上的接口通信。 That in turn is gumming up the whole drawing system. 反过来又使整个绘图系统陷入困境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM