許多 App 第一次安裝開啟時會顯示幾頁操作引導,之後就不再出現。這個功能的關鍵只有一個:如何判斷 App 是不是第一次啟動。答案就是 NSUserDefaults——寫入一個旗標,之後每次啟動都檢查它。
新增一個繼承自 UIViewController 的類別,命名為 UserGuideViewController,內容用 UIScrollView 承載多張圖片,並開啟分頁效果:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
[self initGuide];
}
- (void)initGuide {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 640)];
[scrollView setContentSize:CGSizeMake(1280, 0)]; // 四頁寬度
[scrollView setPagingEnabled:YES]; // 整頁滑動
// 前三頁為純圖片
NSArray *images = @[@"0.png", @"1.png", @"2.png"];
for (int i = 0; i < [images count]; i++) {
UIImageView *imageView = [[UIImageView alloc]
initWithFrame:CGRectMake(320 * i, 0, 320, 460)];
[imageView setImage:[UIImage imageNamed:[images objectAtIndex:i]]];
[scrollView addSubview:imageView];
}
// 最後一頁需要放置按鈕,因此必須開啟使用者互動
UIImageView *lastView = [[UIImageView alloc] initWithFrame:CGRectMake(960, 0, 320, 460)];
[lastView setImage:[UIImage imageNamed:@"3.png"]];
lastView.userInteractionEnabled = YES;
[scrollView addSubview:lastView];
// 在圖片上疊一顆透明按鈕,對應畫面上「開始使用」的位置
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(46, 371, 230, 37)];
[button addTarget:self action:@selector(firstPressed) forControlEvents:UIControlEventTouchUpInside];
[lastView addSubview:button];
[self.view addSubview:scrollView];
}
這裡有個容易忽略的細節:UIImageView 預設 userInteractionEnabled 為 NO,如果不手動設為 YES,疊在上面的 UIButton 永遠不會收到點擊事件。
按鈕的回應方法直接切換到主畫面:
- (void)firstPressed {
WeiBoViewController *vc = [[WeiBoViewController alloc] init];
[self presentViewController:vc animated:YES completion:nil];
}
先引入兩個頭檔:
#import "UserGuideViewController.h" #import "WeiBoViewController.h"
接著在 application:didFinishLaunchingWithOptions: 中做分流:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// 判斷是否為第一次啟動
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"第一次啟動");
// 以引導頁作為根視圖
UserGuideViewController *guide = [[UserGuideViewController alloc] init];
self.window.rootViewController = guide;
} else {
NSLog(@"不是第一次啟動");
WeiBoViewController *main = [[WeiBoViewController alloc] init];
self.window.rootViewController = main;
}
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
寫入 NSUserDefaults 後建議呼叫 synchronize,雖然現代系統會自動處理,但明確呼叫能避免極端情況下旗標未落盘的問題。
此外,若希望引導頁只在「特定版本」顯示(例如 App 更新後新增功能需要重新說明),可以把版本號一起比對:將 CFBundleShortVersionString 存入偏好設定,啟動時比對是否與當前版本相同,不同就顯示引導並更新記錄。這比單純的布林旗標更靈活。
最後,引導頁的 frame 建議改用 Auto Layout 或從 UIScreen.mainScreen.bounds 動態取得,寫死 320×640 在 iPhone 5 以後的各種尺寸上會出現版面錯位。