iOS UIPageControl的圆点间距的设置

方法一:分类法(使用runtime,但是调用了私有的API方法,上传appstroe会被拒的)

#import "UIPageControl+space.h"
#import 

@implementation UIPageControl (space)

+ (void)load
{
    Method origin = class_getInstanceMethod([self class], @selector(_indicatorSpacing));
    Method custom = class_getInstanceMethod([self class], @selector(custom_indicatorSpacing));
    method_exchangeImplementations(origin, custom);
}

- (double)custom_indicatorSpacing
{
    return 12.0;
}
@end

方法二:继承法(继承UIPageControl,通过layoutSubviews从新布局)

#import "CLPageControl.h"
#define dotW 7
#define magrin 5

@implementation CLPageControl

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //计算圆点间距
    CGFloat marginX = dotW + magrin;
    
    //计算整个pageControll的宽度
    CGFloat newW = (self.subviews.count - 1 ) * marginX;
    
    //设置新frame
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, newW, self.frame.size.height);
    
    //设置居中
    CGPoint center = self.center;
    center.x = self.superview.center.x;
    self.center = center;
    
    //遍历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, dotW)];
        }else {
            [dot setFrame:CGRectMake(i * marginX, dot.frame.origin.y, dotW, dotW)];
        }
    }
}

你可能感兴趣的:(iOS UIPageControl的圆点间距的设置)