loadView & ViewDidLoad

本文详细解析了UIViewController中loadView及viewDidLoad方法的功能与调用时机,并通过实例演示了这两种方法的区别及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/loadView


- (void)loadView

Creates the view that the controller manages.

You should never call this method directly. The view controller calls this method when its view property is requested but currently nil.

The method loads or creates a view assigns it to the view property.

该方法用来创建供controller使用的视图。

不能直接调用该方法。 当需要使用view属性但是该属性值为nil时,view controller会调用此方法。该方法加载或创建一个view然后将

它赋值给view属性。


- (void)viewDidLoad

Called after the controller's view is loaded into memory.

This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether

the view hierarchy was loaded from a nib or created programmatically in the loadView method. You usually override this method to 

perform additional initialization on views that were loaded from nib files.


在controller的视图被加载到内存中时被调用

这个方法在view controller的视图层级加载到内存中时被调用。不论视图层级是从nib文件中加载还是在loadView方法中用代码创建。

通常重写这个方法对从nib文件中加载的视图进行额外的初始化。


那么它们之间有什么联系。

UIViewController *controllerA = [[UIViewController alloc]  init];

controllerA.view.backgroundColor = [UIColor blackColor]; //此时会调用loadView方法和viewDidLoad方法

controllerA.view.backgroundColor = [UIColor orangeColor]; //此时不会调用loadView方法和viewDidLoad方法



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值