
在圖片檢視頁點擊右下角「查看評論」時,畫面翻轉進入評論頁;在評論頁點擊左上角「返回」時,往反方向翻回圖片頁。與傳統的導航列過渡相比,實作上其實只多一行程式碼。
這個頁面包含黑色背景、一張圖片,以及右下角的「查看評論」入口:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
// 圖片
UIImageView *myImage = [[UIImageView alloc] initWithFrame:
CGRectMake(0, (SCREENHEIGHT - SCREENWIDTH + 100) / 2,
SCREENWIDTH, SCREENWIDTH - 100)];
myImage.image = [UIImage imageNamed:@"image.jpg"];
[self.view addSubview:myImage];
// 右下角「查看評論」
UILabel *label = [[UILabel alloc] initWithFrame:
CGRectMake(SCREENWIDTH - 100, SCREENHEIGHT - 50, 80, 30)];
label.text = @"查看評論";
label.textColor = [UIColor whiteColor];
label.userInteractionEnabled = YES;
UITapGestureRecognizer *labelTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(viewComment)];
[label addGestureRecognizer:labelTap];
[self.view addSubview:label];
}
// 查看評論
- (void)viewComment {
CommentViewController *commentVC = [[CommentViewController alloc] init];
// animated 必須為 NO,否則會與翻轉動畫衝突
[self.navigationController pushViewController:commentVC animated:NO];
// 從右側翻入
[UIView transitionWithView:self.navigationController.view
duration:1
options:UIViewAnimationOptionTransitionFlipFromRight
animations:nil
completion:nil];
}
重點是順序:先完成 push(animated 設為 NO),再套用 transition。若反過來或 animated 設為 YES,動畫就會失效或出現閃跳。duration 控制動畫時長,options 決定翻轉方向。
系統預設的返回按鈕是帶箭頭的滑動返回,這裡要換成自己的按鈕,才能接上自訂動畫:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// 自訂導航列左側按鈕,取代系統返回鍵
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@"返回" style:UIBarButtonItemStyleBordered
target:self action:@selector(back)];
self.navigationItem.leftBarButtonItem = backButton;
// 圖片
UIImageView *myImage = [[UIImageView alloc] initWithFrame:
CGRectMake((SCREENWIDTH - 300) / 2, (SCREENHEIGHT - 200) / 2 - 100, 300, 200)];
myImage.image = [UIImage imageNamed:@"image.jpg"];
[self.view addSubview:myImage];
// 文字說明
UILabel *label = [[UILabel alloc] initWithFrame:
CGRectMake((SCREENWIDTH - 200) / 2,
myImage.frame.origin.y + myImage.frame.size.height + 20, 200, 30)];
label.text = @"100 個讚,100 條評論";
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
}
// 返回上一頁
- (void)back {
// 這次要先設動畫,再 pop
[UIView transitionWithView:self.navigationController.view
duration:1
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:nil
completion:nil];
[self.navigationController popViewControllerAnimated:NO];
}
返回時順序剛好相反:先套動畫,再執行 pop,且 pop 的 animated 一樣要是 NO。方向參數改為 FlipFromLeft,視覺上就形成「翻回去」的連續感。
interactivePopGestureRecognizer,使用者側滑會走另一套過渡,視覺上不連貫。可在該頁的 viewWillDisappear: 中暫時關閉。 CATransition 或實作 UIViewControllerAnimatedTransitioning 加上 navDelegate,能精細控制 duration、方向與手勢跟手,也更容易在後續維護。整個效果說穿了就是加了兩行 transitionWithView,但「先 push 再動畫」「animated 一律為 NO」這兩個細節如果沒注意到,就會變成怎麼試都不動。偶爾用一次這樣的過渡,確實能為介面加分不少。有疑問歡迎留言交流。