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

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

问题描述

我一直有点不清楚应该分配给 viewDidLoad viewWillAppear 的任务类型:在 UIViewController 子类中。



例如。我正在做一个应用程序,我有一个 UIViewController 子类命中服务器,获取数据,将其提供给视图,然后显示该视图。在 viewDidLoad viewWillAppear


<中执行此操作的优缺点是什么? div class =h2_lin>解决方案

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



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


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

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 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.

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天全站免登陆