Storyboard上でUIPageControlとUIScrollViewを配置してIBOutletとしてPageViewControl.hファイルに接続しておく
また、UIScrollViewのdelegateを配置したUIViewControlに向けておく
PageViewControl.m
// ページ数は最大で11までらしい
#define kNumberOfPages 11
// pageControlの左右がタップされたときに呼ばれる
// scrollViewのスクロール位置をズラして表示を変える
- (void)pageControlDidChange:(UIPageControl *)sender
{
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * sender.currentPage;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
NSLog(@"pageControlDidChange, %d", sender.currentPage);
}
// scrollViewが指で左右にスワイプされたときに呼ばれる
// pageControlの現在ページの表示位置を変更する
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
CGFloat pageWidth = scrollView.frame.size.width;
if (fmod(scrollView.contentOffset.x, pageWidth) == 0.0) {
int pageNum = scrollView.contentOffset.x / pageWidth;
pageControl.currentPage = pageNum;
}
NSLog(@"scrollViewDidScroll %d", pageControl.currentPage);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// UIPageControlをセットアップする
// storyboardで配置していても、これをやらないと表示されない。。
[self.view addSubview:pageControl];
[pageControl addTarget:self action:@selector(pageControlDidChange:) forControlEvents:UIControlEventValueChanged];
// UIScrollViewをセットアップする
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*kNumberOfPages, scrollView.frame.size.height);
// ページごとにUIViewControllerを生成し、view.frameをズラしながらaddSubviewする
CGSize size = scrollView.frame.size;
for (int i=0; i<kNumberOfPages; i++) {
// TODO ここでは適当にページ番号のラベルを表示させている
// 実際はページ数ごとに辞書の配列でも作って持っておいて、ここでそのデータを元に生成する
UIViewController *pageSubView = [[UIViewController alloc] init];
pageSubView.view.frame = CGRectMake(size.width*i, 0, size.width, size.height);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((size.width-200)/2, 100, 200, 200)];
[label setTextAlignment:UITextAlignmentCenter];
UIFont *font = [UIFont systemFontOfSize:40.0f];
[label setFont:font];
label.text = [[NSString alloc] initWithFormat:@"%d", i+1];
[[pageSubView view] addSubview:label];
[scrollView addSubview:pageSubView.view];
}
}