UIViewController viewDidLoad vs. viewWillAppear:正确的分工是什么? [英] UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

查看:17
本文介绍了UIViewController viewDidLoad vs. viewWillAppear:正确的分工是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直不太清楚应该分配给 viewDidLoadviewWillAppear 的任务类型:在 UIViewController 子类中.

I have always been a bit unclear on the type of tasks that should be assigned to viewDidLoad vs. viewWillAppear: in a UIViewController subclass.

例如我正在做一个应用程序,我有一个 UIViewController 子类访问服务器,获取数据,将其提供给视图,然后显示该视图.在 viewDidLoadviewWillAppear 中这样做的优缺点是什么?

e.g. I am doing an app where I have a UIViewController subclass hitting a server, getting data, feeding it to a view and then displaying that view. What are the pros and cons of doing this in viewDidLoad vs. viewWillAppear?

推荐答案

viewDidLoad 是你必须做一次的事情.每次出现视图时都会调用 viewWillAppear.你应该做一些你只需要在 viewDidLoad 中做一次的事情——比如设置你的 UILabel 文本.但是,您可能希望在用户每次查看时修改视图的特定部分,例如每次您转到正在播放"视图时,iPod 应用程序都会将歌词滚动回顶部.

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

但是,当您从服务器加载内容时,您还必须考虑延迟.如果您将所有网络通信打包到 viewDidLoad 或 viewWillAppear 中,它们将在用户看到视图之前执行 - 可能导致您的应用程序短暂冻结.首先向用户显示带有某种活动指示器的未填充视图可能是个好主意.当您完成网络连接时,这可能需要一两秒钟(甚至可能会失败 - 谁知道?),您可以使用您的数据填充视图.可以在各种 twitter 客户端中看到关于如何做到这一点的好例子.例如,当您在 Twitterrific 中查看作者详细信息页面时,该视图只会显示正在加载...",直到网络查询完成.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

这篇关于UIViewController viewDidLoad vs. viewWillAppear:正确的分工是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆