iOS自定义UIPageControl,做一个漂亮的滚动视图

iOS自定义UIPageControl,做一个漂亮的滚动视图_第1张图片


写一些需要注意的事项:

pagecontrol的frame设置时候尽量用bound,否则会出现不可预料问题

pagecontrol的subviews是个view的数组,而不是UIImageView(网上的资料全说是UIImageView,已经是之前版本了,可以log一下看看)


自定义PageController

@interface DiyPageController : UIPageControl {
    UIImage * _imagePageNomal;
    UIImage * _imagePageHighlited;
}
- (id)initWithFrame:(CGRect)frame;
@end

@implementation DiyPageController
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    _imagePageNomal = [UIImage imageNamed:@"ADPicSlideIcon"];
    _imagePageHighlited = [UIImage imageNamed:@"ADPicSlideIconActive"];
    return self;
}
- (void)setCurrentPage:(NSInteger)currentPage {
    [super setCurrentPage:currentPage];
    [self updateDots];
}
-(void) updateDots {
    for (int i = 0; i < [self.subviews count]; i++) {
        UIView * dot = [self.subviews objectAtIndex:i];
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(-2, -2, 10, 10)];

//        CGSize size;
//        size.height = 1;     //自定义圆点的大小
//        size.width = 1;      //自定义圆点的大小,下边注释set方法是设置view的frame
//        [dot setFrame:CGRectMake(dot.frame.origin.x, dot.frame.origin.y, size.width, size.width)];
        imageView.image = (i == self.currentPage) ? _imagePageHighlited : _imagePageNomal;
        [dot addSubview:imageView];

        
    }
}

添加pageController

- (void)createPageController{
    //实例化页面管理
    _pageController = [[DiyPageController alloc] initWithFrame:CGRectMake(0, 60, self.bounds.size.width, 20)];
//    _pageController.center = CGPointMake(ScreenWidth / 2, 60);
    //一共有多少页(滚动循环多了两张)
    _pageController.numberOfPages = 3;
    //设置选中页
    _pageController.currentPage = 0;
    //设置点击换页码   默认no(切换)
    _pageController.defersCurrentPageDisplay = NO;
    //设置背景色
    //    _pageController.backgroundColor = RandomColor;
    
    //给pageControl添加行为
//    [_pageController addTarget:self action:@selector(pageNumberChanged:) forControlEvents:UIControlEventValueChanged];
//    [_pageController addTarget:self action:@selector(pageControlContinusScroll:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:_pageController];
}

设置scroll的代理,更新显示

#pragma mark scrollViewDelegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    _pageController.currentPage = _scrollView.contentOffset.x / ScreenWidth;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _pageController.currentPage = _scrollView.contentOffset.x / ScreenWidth;
}

通过设置着两个代理方法,保证不论是自动滑动还是手动滑动都将会更新pagecontrol


你可能感兴趣的:(iOS自定义UIPageControl,做一个漂亮的滚动视图)