改变UIPageControl圆点间距

早上设计让我改一下UIPageControl圆点间距,浏览了不少文章,发现居然没有好的解决办法,stackoverflow上建议用第三方,下了一个第三方实现,发现达不到我要的效果。本着研究(zhuang bi)的精神,我决定要研究一下。

UIPageControl并没有什么属性可以设置,用来改变间距。那么只能运行时了。先看一下这个类有哪些属性,包括隐藏的。

    Ivar * ivars = class_copyIvarList([UIPageControl class], &outCount);

    for (int i = 0; i<outCount; i++) {

        Ivar ivar = ivars[i];

        NSLog(@"%s", ivar_getName(ivar));
    }

好吧,结果我不贴了,并没有找到什么有用的成员变量,可以控制的。

那么接着看一下私有方法

    Method * imod = class_copyMethodList([UIPageControl class], &outCount);
    for (int i = 0; i < outCount; i++) {
        
        Method mod = imod[i];
        
        NSLog(@"%s", method_getName(mod));
        
        
        NSLog(@"ret: %s", method_copyReturnType(mod));
    }

浏览了一下,发现一个函数,_indicatorSpacing。这货长的就像我们要找的。

先放源码

//.h

#import <Foundation/Foundation.h>

@interface UIPageControl (Distance)

@end

//.m #import "UIPageControl+Distance.h" #import <objc/runtime.h> @implementation UIPageControl (Distance) + (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 6.0; } @end
custom_indicatorSpacing最开始写的时候,返回值写的float。发现圆点间距变成0了。。。。。醉了,根本找不到原因。

NSLog(@"ret: %s", method_copyReturnType(mod));打印了一下它的返回值类型,结果是'd'。当时没留意和float的区别。后来才想到把custom_indicatorSpacing返回值类型改成double。然后。。。就可以正常改变圆点的间距了。估计是因为double比float长吧。知道原因的大牛可以分享给我。

尼玛,因为调用私有API过不了app store 审核。

原文地址:https://www.cnblogs.com/chyl411/p/5421668.html