很多人寫 iOS 一兩年,仍然分不清 loadView、viewDidLoad、viewWillAppear: 各自該做什麼、又跑幾次。這個範例刻意在每個方法裡印出方法名稱,讓呼叫順序一目了然。
#import "AppDelegate.h"
#import "RootViewController.h"
@implementation AppDelegate
- (void)dealloc {
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
[_window release];
// 1. 建立根視圖控制器
RootViewController *rootVC = [[RootViewController alloc] init];
// 2. 交給 window
self.window.rootViewController = rootVC;
[rootVC release];
return YES;
}
@end
#import "RootViewController.h"
#import "SecondViewController.h"
#define HEIGHT self.view.frame.size.height
@interface RootViewController () <UITextFieldDelegate>
@property (nonatomic, retain) NSMutableArray *arr;
@end
@implementation RootViewController
// 初始化:容器類物件在這裡準備最合適
// 這個方法系統會自己呼叫,不需要我們主動觸發
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.arr = [NSMutableArray array];
}
NSLog(@"%s", __FUNCTION__);
return self;
}
// view 的懶載入:一般情況會呼叫 super,只有在完全自繪時才自己建
- (void)loadView {
[super loadView];
NSLog(@"%s", __FUNCTION__);
}
#pragma mark 視圖將要出現
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"%s", __FUNCTION__);
}
#pragma mark 視圖已經出現
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"%s", __FUNCTION__);
}
#pragma mark 視圖將要消失
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSLog(@"%s", __FUNCTION__);
}
#pragma mark 視圖已經消失
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated]; // 注意:這裡原本誤寫成 viewDidAppear
NSLog(@"%s", __FUNCTION__);
}
#pragma mark 視圖的創建與佈局都在這裡
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor];
UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(100, 200, 150, 40)];
textField1.layer.borderWidth = 1;
textField1.layer.cornerRadius = 10;
[self.view addSubview:textField1];
textField1.delegate = self;
[textField1 release];
UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(100, 300, 150, 40)];
textField2.layer.borderWidth = 1;
textField2.layer.cornerRadius = 10;
[self.view addSubview:textField2];
textField2.delegate = self;
[textField2 release];
UITextField *textField3 = [[UITextField alloc] initWithFrame:CGRectMake(100, 400, 150, 40)];
textField3.layer.borderWidth = 1;
textField3.layer.cornerRadius = 10;
[self.view addSubview:textField3];
textField3.delegate = self;
[textField3 release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(100, 500, 150, 40);
[button setTitle:@"下一頁" forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
button.layer.borderWidth = 1;
button.layer.cornerRadius = 10;
}
#pragma mark - 鍵盤遮擋處理
// 開始編輯時,若輸入框在畫面下半部,就把整個 view 往上推
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (textField.frame.origin.y > HEIGHT / 2) {
CGFloat height = textField.frame.origin.y - HEIGHT / 2;
self.view.center = CGPointMake(self.view.center.x, self.view.center.y - height);
}
return YES;
}
// 結束編輯時再推回原位
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if (textField.frame.origin.y > HEIGHT / 2) {
CGFloat height = textField.frame.origin.y - HEIGHT / 2;
self.view.center = CGPointMake(self.view.center.x, self.view.center.y + height);
}
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#pragma mark - 跳轉
- (void)click:(UIButton *)button {
SecondViewController *secondVC = [[SecondViewController alloc] init];
secondVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:secondVC animated:YES completion:nil];
[secondVC release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
#import "SecondViewController.h"
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(100, 100, 100, 30);
button.layer.borderWidth = 1;
button.layer.cornerRadius = 10;
[self.view addSubview:button];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)click:(UIButton *)button {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
viewDidDisappear: 裡誤寫成呼叫 [super viewDidAppear:animated],這會造成父類的消失事件沒有被正確通知,應該是 [super viewDidDisappear:animated]。self.view.center,副作用是所有子視圖一起位移,且與 navigation bar、tab bar 的座標關係容易出錯。較穩妥的做法是用 contentInset/contentOffset 調整 scrollView,或改用約束配合鍵盤高度動畫。把這六個方法的呼叫時機記牢,之後處理「回頁面要刷新」「鍵盤要避開」這類問題時,就不會再猜該寫在哪裡了。