UIPageControl设置圆点之间距离

自定义UIPageControl,重写layoutSubviews方法

#import "XDPageControl.h"
#define dotW 22 // 圆点宽
#define dotH 7  // 圆点高
#define magrin 8    // 圆点间距
@implementation XDPageControl

- (void)layoutSubviews
{
    [super layoutSubviews];
    //计算圆点间距
    CGFloat marginX = dotW + magrin;
    
    //计算整个pageControll的宽度
    CGFloat newW = (self.subviews.count - 1 ) * marginX;
    
    //设置新frame
    self.frame = CGRectMake(kScreenW/2-(newW + dotW)/2, self.frame.origin.y, newW + dotW, self.frame.size.height);
    
    //遍历subview,设置圆点frame
    for (int i=0; i<[self.subviews count]; i++) {
        UIImageView* dot = [self.subviews objectAtIndex:i];
        
        if (i == self.currentPage) {
            [dot setFrame:CGRectMake(i * marginX, dot.frame.origin.y, dotW, dotH)];
        }else {
            [dot setFrame:CGRectMake(i * marginX, dot.frame.origin.y, dotW, dotH)];
        }
    }
}
@end

调用的时候还可以自定义图片
    _pageControl = [[XDPageControl alloc] init];
    _pageControl.frame = CGRectMake(0, kScreenH-75*kscale, kScreenW, 20);//指定位置大小
    _pageControl.numberOfPages = 3;//指定页面个数
    _pageControl.currentPage = 0;//指定pagecontroll的值,默认选中的小白点(第一个)

    // 设置成圆点颜色
//    _pageControl.pageIndicatorTintColor =[UIColor yellowColor];
//    _pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
    
    // 设置成图片
    [_pageControl setValue:[UIImage imageNamed:@"icon_dot_normal"] forKeyPath:@"_pageImage"];
    [_pageControl setValue:[UIImage imageNamed:@"icon_dot_height"] forKeyPath:@"_currentPageImage"];
    [self.view addSubview:_pageControl];






你可能感兴趣的:(iOS开发)