简体   繁体   English

快速加载多个视图

[英]Loading multiple views asynchronous in swift

I was wondering how someone would load multiple UI elements asynchronously. 我想知道有人如何异步加载多个UI元素。 In my case, I have a UIViewController that has a UISegmentControl . 就我而言,我有一个具有UISegmentControlUIViewController Each segment has different UI aspects to load. 每个细分都有不同的UI方面要加载。
For example seg1 shows one image, seg2 shows and image and some text, etc. 例如seg1示出了一个图像, seg2节目和图像和一些文本等

If I load all the UI elements before showing the UIViewController then there is a noticeable lag. 如果在显示UIViewController之前加载了所有UI元素,则会有明显的滞后。 So I would want to load seg2...n asynchronously to make the UI feel more responsive. 因此,我想异步加载seg2...n以使UI响应更快。

Would I need to load everything via 我需要通过加载所有内容吗

DispatchQueue.main.async { 
    // load UI
}

For each seg I want to load in the background? 对于每个要在后台加载的seg Or can I load these elements on another thread and not take up the main thread? 还是可以将这些元素加载到另一个线程上而不占用主线程? I know you're not supposed to update the UI on background threads... But will using the main thread still block the UI if I use async code? 我知道您不应该在后台线程上更新UI ...但是如果我使用异步代码,使用主线程是否仍会阻塞UI?

You can't make UI changes on a background thread. 您不能在后台线程上更改UI。 Nearly all UIKit calls must be made on the main thread. 几乎所有UIKit调用都必须在主线程上进行。 Therefore you're likely out of luck. 因此,您可能不走运。

Instead what you should do is do the time consuming number-crunching (downloading and parsing data for example) on a background thread and then use DispatchQueue.main.async() to install the data into your views on the main thread once the time consuming work is done. 相反,您应该做的是在后台线程上执行耗时的数字运算(例如下载和解析数据),然后在耗时使用DispatchQueue.main.async()将数据安装到主线程上的视图中工作完成了。

If it's the UI setup that is introducing the lag and it's not possible to speed it up then you may be out of luck. 如果是UI设置引入了延迟,并且无法加快延迟,那么您可能就不走运了。

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

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