本文分享一個常見場景:在 iOS 開發中用程式碼建立自訂按鈕,點擊後彈出另一個視圖,再從新視圖返回。
剛學 iOS 時,視圖切換用 Storyboard 拖一條線就完成了。不過實際做過之後會發現,用程式碼控制視圖切換更為靈活,也更清楚每一步發生了什麼。以下就從 this 開始記錄。
新建工程後,建立兩個 UIViewController 類別,姑且稱 A 與 B。AppDelegate 的設定這裡省略,相信看到這裡的人都知道怎麼指定 root 視圖。
目標是:從 A 點擊按鈕彈出 B,再從 B 點擊按鈕返回 A。
- (void)viewDidLoad
{
[super viewDidLoad];
// 設定視圖背景顏色
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
// 建立彈出模態視圖的按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 設定按鈕位置與大小
[button setFrame:CGRectMake(120, 220, 80, 40)];
// 設定按鈕文字與狀態
[button setTitle:@"模態視圖" forState:UIControlStateNormal];
// 綁定動作
[button addTarget:self action:@selector(modelViewGO) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void) modelViewGO
{
BViewController *modalView = [[BViewController alloc] init];
modalView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:modalView animated:YES completion:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor purpleColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(130, 50, 60, 20)];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
-(void)back
{
// 移除彈出的模態視圖,第一個參數控制是否帶動畫,
// 第二參數是回調 block,模態視圖消失後會回到這裡
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@"back"); // 在此處設中斷點可驗證回調確實觸發
}];
}
預設效果是從下往上彈出,可透過 modalTransitionStyle 更換:
modalView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
typedef NS_ENUM(NSInteger, UIModalTransitionStyle) {
UIModalTransitionStyleCoverVertical = 0, // 預設垂直向上
UIModalTransitionStyleFlipHorizontal, // 翻轉
UIModalTransitionStyleCrossDissolve, // 淡入淡出
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
UIModalTransitionStylePartialCurl, // 翻頁
#endif
};
需要留意的地方:在模態視圖上點擊返回後,該視圖物件會被釋放,因此凡是附加在這個視圖上的資源,都應該寫在 dealloc 方法中處理,否則容易出現記憶體洩漏或後續操作時的意外行為。