[英]loadview getting called infinite times
我的應用程序ViewController1.m
和ViewController2.m
有兩個ViewController2.m
。
在AppDelegate
我有這個代碼。
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
self.viewController = [[ViewController1 alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
}
else
{
self.viewController = [[ViewController1 alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
}
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
在ViewController1.m中我添加了一個按鈕,然后在按鈕上單擊我正在顯示另一個視圖控制器ViewController2.m
如下所示:
ViewController2 * obj = [[ViewController2 alloc] initWithNibName:nil bundle:nil];
[self.view addSubview:obj.view];
在ViewController2.m的loadView
,我添加了另一個這樣的按鈕
NSLog(@"\n Load view called");
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(onButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Back to previous view" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
當我運行我的應用程序時,單擊ViewController1.m中的按鈕,應用程序掛起並且ViewController2.m的loadView
開始無限調用。
我不知道這個問題背后的原因,我只想在點擊按鈕上加載另一個ViewController而我沒有使用任何導航控制器。
有人能指出這個問題背后的原因嗎?
不要在loadView
執行此操作。 而是將您的代碼移動到viewDidLoad
。 問題是你所訪問self.view
內loadView
,基本要求loadView
因為初始呼叫loadView
再也沒有回來。
對不起繞口令...當視圖尚未實例化時,會自動調用loadView
。 僅在返回時才進行視圖初始化。 如果它沒有返回並且您嘗試訪問view
屬性,它將再次調用它。 在你的情況下,它是遞歸的,因為你仍然在loadView
方法中。
來自文檔 :
視圖控制器在請求其view屬性但當前為nil時調用此方法。 此方法加載或創建視圖並將其分配給view屬性。
當您使用initWithNibName
請不要使用loadView
。 這是一個錯誤的設計。 如果您不想使用viewDidLoad
並想要初始化階段的某些內容,則覆蓋此方法,
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// write your init code here.
}
return self;
}
loadView
的專有工作是設置viewControllers視圖屬性。 這可能是這樣的
self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
想象一下,你的view屬性的getter看起來像這樣:
if(!_view)
[self loadView];
return _view;
這意味着如果在設置視圖之前使用self.view(如在loadView中),則會反復調用loadView。 我的建議通常是避免重寫loadView,而是創建一個從awakeFromNib
和initWithNib...
調用的簡單configureView
方法initWithNib...
這樣可以從storyboard或nib中正確創建視圖,或者通過代碼實例化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.