早上設計讓我改一下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 審核。