本文以一個密碼生成器範例說明 iOS 開發流程,重點在於使用純程式碼建立畫面,並透過 MVC 概念區分視圖、控制器與事件邏輯。相較於純粹拉介面,純程式碼方式更能釐清元件建立與布局的細節。
程式主要包含兩個畫面:主頁面 MainView 與說明頁面 InfomationView。兩者互斥顯示,透過根視圖中的按鈕或導覽列切換。
可使用 UIView 動畫 API 做出翻頁效果:
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0f];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[self removeMainView];
[UIView commitAnimations];
UINavigationItem 可包含左按鈕、標題文字與右按鈕:
UINavigationBar *bar = [[UINavigationBar alloc] init];
[self.view insertSubview:bar aboveSubview:self.infomationViewController.view];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"About Password Generator"];
[bar pushNavigationItem:item animated:YES];
UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
style:UIBarButtonItemStylePlain
target:self
action:@selector(SwitchView)];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStylePlain
target:self
action:@selector(SwitchView)];
item.leftBarButtonItem = leftBarButton;
item.rightBarButtonItem = rightBarButton;
若使用程式化布局,建議在視圖即將出現時重新計算 frame,避免初次顯示時位置錯誤:
- (void)viewWillAppear:(BOOL)animated {
[self reLayout];
[super viewWillAppear:animated];
}
純程式碼建立 UI 雖然較繁瑣,但能更清楚掌握每個元件的位置與生命週期。實作時建議先拆分視圖與控制器,再逐步加入動畫與互動,最後統一處理布局,能有效降低混亂。