[英]iOS viewDidLoad for UIView
在ViewController中,有ViewDidLoad
可以知道VC何時加載。
對於UIView,在加載視圖時我必須使用什么方法?
是否可以使用任何init調用此方法?
編輯:沒有XIB,只是以編程方式。
實際上,對於視圖的初始化,您不必對視圖控制器的方法viewDidLoad()執行任何操作。 您想要做的就是,您可以在視圖的init方法中執行。 例如,在視圖控制器的viewDidLoad()中,有一些初始化代碼:
- (void)viewDidLoad{
[super viewDidLoad];
// init your parameters here
}
類似地,在您的視圖的init方法中:
- (id)initWithDelegate:(id)_delegate
{
self = [[[[NSBundle mainBundle] loadNibNamed:@"YourView" owner:self options:nil] objectAtIndex:0] retain];
if (self) {
[super init];
self.delegate = _delegate;
// init your parameters here
return self;
}
return nil;
}
然后,您從視圖控制器創建YourView,如下所示:
YourView view = [[YourView alloc] initWithDelegate:self];
[self.view addSubview:view];
[view release];
此外,您在視圖加載時要執行的操作,可以在視圖中放置layoutSubviews方法,如下所示:
-(void)layoutSubviews{
[super layoutSubviews];
// init your parameters here, like set up fonts, colors, etc...
}
我想,這就是你所需要的。
干杯!
斯威夫特2:
import UIKit
class myView: UIView {
override func layoutSubviews() {
print("run when UIView appears on screen")
// you can update your label's text or etc.
}
}
你可以使用willMove(toSuperview newSuperview:UIView?)
import UIKit
final class myView: UIView {
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
//Do stuff here
}
}
我有類似的問題,發現相對容易的解決方案。 想法是在適當的時間將viewDidLoad發送到每個子視圖,並在您感興趣的類上重載該方法。
為此,在您的類中添加這部分代碼......
// UIViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view viewDidLoad];
}
// UIView+Loading.m
#import < UIKit/UIKit.h>
@implementation UIView (Loading)
- (void)viewDidLoad
{
for (UIView* subview in self.subviews)
[subview viewDidLoad];
}
@end
// UIView+Loading.h
#import < UIKit/UIKit.h>
@interface UIView (Loading)
- (void)viewDidLoad;
@end
// UIView_CustomImplementation
- (void)viewDidLoad
{
NSLog(@"Do whatever you want to do in custom UIView after method viewDidLoad on UIViewController was called");
}
據我所知,除了init之外,我認為沒有這樣的方法。 通常我會在init方法中做准備。 您可以創建自己的viewDidLoad
方法並手動調用它。 但大部分時間,UIView由它的視圖控制器管理,因此視圖控制器應該知道何時加載視圖,如果要配置視圖,則可以在視圖控制器中進行。 順便說一句,並不總是調用viewDidLoad
方法。
它不像這樣工作。
- (void)viewDidLoad
在加載視圖控制器時不調用- (void)viewDidLoad
; 加載視圖控制器視圖時調用它。
因此,您可以創建UIViewController,並且將調用的唯一方法是用於初始化它的init方法。 將不會創建視圖,不會調用 - (void)viewDidLoad方法等。
然后,當其他東西要求視圖控制器查看其視圖時,通過:
viewController.view;
視圖控制器然后調用:
- (void)loadView; // This is where you put your own loading view information, and set the viewController's self.view property here.
其次是:
- (void)viewDidLoad;
View Did Load是一個單獨的方法,因此您不必中斷實際的loadView方法和復雜的視圖加載選項。 在使用nibs等時對子類進行子類化和覆蓋會導致問題,因為開發人員不確定Apple正在做什么以及他們的最佳實踐是什么,因此Apple將這種方法分離出來是很明智的。
然后,當一個內存警告到來時,視圖被釋放,並設置為nil:
- (void)viewWillUnload;
// view unloaded and set to nil.
- (void)viewDidUnload;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.