美文网首页零碎知识点iOS 开发 学习iOS Developer
iOS UIPageControl的圆点间距的设置

iOS UIPageControl的圆点间距的设置

作者: 逍遥晨旭 | 来源:发表于2017-03-10 15:50 被阅读3452次

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

    #import "UIPageControl+space.h"
    #import <objc/runtime.h>
    
    @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)];
            }
        }
    }

    相关文章

      网友评论

      • 代亮真的不会亮:最后循环的时候,if和else里面的完全一模一样,抄也抄的专业点,好伐?
        七肋:作者应该是故意这样写的。好让人自己修改currentPage下的frame。
      • WillyGeek:感谢分享的思路. 实测发现继承法计算宽度不是很准确

      本文标题:iOS UIPageControl的圆点间距的设置

      本文链接:https://www.haomeiwen.com/subject/vpwqgttx.html