【iOS】UIPageControlを利用したスライドページ作成
こんにちは!久しぶりの更新になってしまいました。
アプリの操作などは初回起動時にツアーなどを表示させて説明したいですよね。そんな時には「UIPageControl」を利用すると簡易的なスライドページを作ることができます。
サンプルコード
UIPageCongrolを利用して各ページをスライドさせるには、UIScrollViewが必要です。
サンプルでは表示するページ数に応じてUILabelで現在のページ数が分かるように表示しています。
hogeViewController.h
@interface hogeViewController : UIViewController<UIScrollViewDelegate> @property(nonatomic,strong) UIScrollView *scrollView; @property(nonatomic,strong) UIPageControl *pageControl; @end
hogeViewController.m
- (void)viewDidLoad { [super viewDidLoad]; NSInteger pageSize = 4; // ページ数 CGFloat width = self.view.bounds.size.width; CGFloat height = self.view.bounds.size.height; // UIScrollViewのインスタンス化 scrollView = [[UIScrollView alloc]init]; scrollView.backgroundColor = [UIColor lightGrayColor]; scrollView.frame = self.view.bounds; // 横スクロールのインジケータを非表示にする scrollView.showsHorizontalScrollIndicator = NO; // ページングを有効にする scrollView.pagingEnabled = YES; scrollView.userInteractionEnabled = YES; scrollView.delegate = self; // スクロールの範囲を設定 [scrollView setContentSize:CGSizeMake((pageSize * width), height)]; // スクロールビューを貼付ける [self.view addSubview:scrollView]; // スクロールビューにラベルを貼付ける for (int i = 0; i < pageSize; i++) { // UILabel作成 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(i * width, 0, width, height)]; label.text = [NSString stringWithFormat:@"%d", i + 1]; label.font = [UIFont fontWithName:@"Arial" size:92]; label.backgroundColor = [UIColor blueColor]; label.textAlignment = NSTextAlignmentCenter; [scrollView addSubview:label]; NSLog(@"imagenum:%d",i); } // ページコントロールのインスタンス化 CGFloat x = (width - 300) / 2; pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(x, 430, 300, 50)]; // 背景色を設定 pageControl.backgroundColor = [UIColor whiteColor]; // ページ数を設定 pageControl.numberOfPages = pageSize; // 現在のページを設定 pageControl.currentPage = 0; // デフォルトの色 self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor]; // 選択されてるページを現す色 self.pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:1.0]; // ページコントロールをタップされたときに呼ばれるメソッドを設定 pageControl.userInteractionEnabled = YES; [pageControl addTarget:self action:@selector(pageControl_Tapped:) forControlEvents:UIControlEventValueChanged]; // ページコントロールを貼付ける [self.view addSubview:pageControl]; }
ページング処理
// スクロールビューがスワイプされたとき - (void)scrollViewDidScroll:(UIScrollView *)_scrollView { CGFloat pageWidth = scrollView.frame.size.width; if ((NSInteger)fmod(scrollView.contentOffset.x , pageWidth) == 0) { // ページコントロールに現在のページを設定 pageControl.currentPage = scrollView.contentOffset.x / pageWidth; } } // ページコントロールがタップされたとき - (void)pageControl_Tapped:(id)sender { CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * pageControl.currentPage; [scrollView scrollRectToVisible:frame animated:YES]; }
実行結果
表示領域を色分けしています。また、ページコントロールのデフォル色と選択色をレイアウトに合わせて指定します。

コメントをどうぞ