LoginSignup
2
5

More than 5 years have passed since last update.

UIPageControlとUIScrollViewを連動させる

Last updated at Posted at 2015-02-11

概要

UIScrollViewをスクロールした際に、UIPageControlの該当箇所を選択させる仕組みをつくります。

コード

デフォルトでコードに挿入されている部分は省くので自分で補ってください。
また、すでにScrollViewの設定が終わった状態の前提でコードを書いています。

UIパーツの定義

ScrollAndSegmentedControlViewController.h
@interface ProfileViewController : AppViewController<UIActionSheetDelegate, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *userScrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *userPageControl;

@end

ロジックの実装

ScrollAndSegmentedControlViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.userScrollView.delegate = self;
    [self.userPageControl addTarget:self
                             action:@selector(tappedPageControl:)
                   forControlEvents:UIControlEventValueChanged];
}

// UIScrollView delegate method
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    if ((NSInteger)fmod(scrollView.contentOffset.x , pageWidth) == 0) {
        // set current page at pageControl
        self.userPageControl.currentPage = scrollView.contentOffset.x / pageWidth;
    }
}

// when tapped pageControl
- (void)tappedPageControl:(id)sender
{
    CGRect frame = self.userScrollView.frame;
    frame.origin.x = frame.size.width * self.userPageControl.currentPage;
    [self.userScrollView scrollRectToVisible:frame animated:YES];
}
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5