首次開啟 App 時,用幾張半透明圖片加說明文字告訴使用者主要功能在哪,是很常見的引導手法。以下整理實作思路與完整程式碼。
pagingEnabled 設為 YES,即可實現整頁吸附式滑動。@interface ViewController : UIViewController <UIScrollViewDelegate>
{
UIScrollView *helpScrView;
UIPageControl *pageCtrl;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
CGRect bounds = self.view.frame;
// 建立蒙版圖片(以單張為例)
UIImageView *imageView1 = [[[UIImageView alloc]
initWithFrame:CGRectMake(bounds.origin.x, bounds.origin.y,
bounds.size.width, bounds.size.height)] autorelease];
[imageView1 setImage:[UIImage imageNamed:@"help01.png"]];
imageView1.alpha = 0.5f; // 半透明
// 其餘圖片以 similarly 方式建立,並以遞增的 origin.x 橫向排列
// ...
// 建立 ScrollView
helpScrView = [[UIScrollView alloc]
initWithFrame:CGRectMake(bounds.origin.x, bounds.origin.y,
bounds.size.width, bounds.size.height)];
// 三張圖,內容寬度為畫面寬度 × 3
[helpScrView setContentSize:CGSizeMake(bounds.size.width * 3, bounds.size.height)];
helpScrView.pagingEnabled = YES; // 整頁滑動
helpScrView.bounces = NO; // 取消彈性回彈,可依喜好調整
[helpScrView setDelegate:self];
helpScrView.showsHorizontalScrollIndicator = NO; // 用 UIPageControl 取代內建捲軸
[helpScrView addSubview:imageView1];
[self.view addSubview:helpScrView];
// 建立 UIPageControl
pageCtrl = [[UIPageControl alloc]
initWithFrame:CGRectMake(0, bounds.size.height - 30, bounds.size.width, 30)];
pageCtrl.numberOfPages = 3;
pageCtrl.currentPage = 0;
[pageCtrl addTarget:self
action:@selector(pageTurn:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pageCtrl];
}
這裡有個關鍵細節常被遺漏:每張蒙版圖的 frame 必須橫向錯開,也就是第 n 張的 origin.x 等於 n × 螢幕寬度。若全部疊在同一個位置,滑動時只會看到同一張圖。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
CGPoint offset = scrollView.contentOffset;
CGRect bounds = scrollView.frame;
[pageCtrl setCurrentPage:offset.x / bounds.size.width];
}
- (void)pageTurn:(UIPageControl *)sender {
CGSize viewSize = helpScrView.frame.size;
CGRect rect = CGRectMake(sender.currentPage * viewSize.width, 0,
viewSize.width, viewSize.height);
[helpScrView scrollRectToVisible:rect animated:YES];
}
在 viewDidUnload(iOS 6 以後請改用 didReceiveMemoryWarning 或 dealloc)中釋放 UIScrollView 與 UIPageControl。若這些物件是以 ARC 強引用持有,記得在引導結束時把 helpScrView 與 pageCtrl 從 superview 移除並設為 nil。
只顯示一次。 引導蒙版應該在首次啟動後寫入 NSUserDefaults 標記,後續啟動直接跳過。
加入淡入淡出。 把 helpScrView 的 alpha 從 0 動畫到 1,體驗會比突然出現好很多。
最後一頁放行動呼籲。 在 pageTurn 或 scrollViewDidEndDecelerating 中判斷 currentPage 是否為最後一頁,若是則顯示「開始使用」按鈕,點擊後一起移除整個蒙版。
modern 替代方案。 若只是想顯示幾段說明,UIPageViewController 提供的原生翻頁手勢與轉場動畫會更流暢,值得優先評估。