本文分享在 iOS 開發中,如何透過自訂按鈕跳轉到另一個視圖,這個場景在實務中非常常見。
剛學 iOS 不久,雖然視圖切換能直接用 Storyboard 拉線搞定,但用程式碼控制視圖其實更為靈活。以下就開始今天的筆記。
新建工程後,建立兩個 UIViewController 類別,假設為 A 與 B。這裡省略 AppDelegate 的程式碼,相信看到這裡的人都知道如何設定 root 視圖。
目標是:從 A 點擊按鈕彈出 B 視窗,再點 B 的按鈕返回 A。
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];
}
接著在 B 視圖加入返回按鈕:
- (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 {
// 移除模態視圖,第一個參數控制是否有動畫;帶 completion 的版本可在移除後回調
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@"back"); // 點擊返回、模態視圖移除後會回到這裡
}];
}
預設動畫是由下往上彈出,可透過 modalTransitionStyle 改成其他效果:
typedef NS_ENUM(NSInteger, UIModalTransitionStyle) {
UIModalTransitionStyleCoverVertical = 0, // 預設垂直向上
UIModalTransitionStyleFlipHorizontal, // 翻轉
UIModalTransitionStyleCrossDissolve, // 淡入淡出
UIModalTransitionStylePartialCurl, // 翻頁
};
需注意的是:在模態視圖上點擊返回後,該視圖對象會被徹底釋放,因此記得把加到該視圖上的對象寫在 dealloc 方法中。