開源的 GrayPageControl 提供了「用自訂圖片取代 UIPageControl 預設圓點」的能力,做法是自己呼叫 updateDots 去改寫每一個 dot 的 image。問題是 iOS 7 徹底修改了 UIPageControl 的內部檢視結構,原本假設「每個 dot 直接就是 UIImageView」的程式碼便會失效甚至崩潰。
在 iOS 6 及更早版本中,UIPageControl 的 subviews 就是一個個 UIImageView。到了 iOS 7,每個 dot 變成被包在一層 UIView 裡,UIImageView 退到第二層。因此遍歷 self.subviews 時拿到的型別錯了,直接設定 image 不會有任何效果,某些寫法則會引發異常。
關鍵在於 updateDots 要往下多走一層去找 UIImageView,找不到時再自行補上:
#import "GrayPageControl.h"
@implementation GrayPageControl
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
activeImage = [UIImage imageNamed:@"active_page_image"];
inactiveImage = [UIImage imageNamed:@"inactive_page_image"];
[self setCurrentPage:1];
}
return self;
}
- (id)initWithFrame:(CGRect)aFrame
{
if (self = [super initWithFrame:aFrame]) {
activeImage = [UIImage imageNamed:@"active_page_image"];
inactiveImage = [UIImage imageNamed:@"inactive_page_image"];
[self setCurrentPage:1];
}
return self;
}
- (void)updateDots
{
for (int i = 0; i < [self.subviews count]; i++)
{
UIView *dotView = [self.subviews objectAtIndex:i];
UIImageView *dot = nil;
// 重點:iOS 7 之後 dot 被包了一層 UIView,要往下找
for (UIView *subview in dotView.subviews)
{
if ([subview isKindOfClass:[UIImageView class]])
{
dot = (UIImageView *)subview;
break;
}
}
// 找不到就自己補一個,相容舊版結構
if (dot == nil)
{
dot = [[UIImageView alloc]
initWithFrame:CGRectMake(0.0f, 0.0f,
dotView.frame.size.width,
dotView.frame.size.height)];
[dotView addSubview:dot];
}
if (i == self.currentPage) {
if (activeImage) dot.image = activeImage;
} else {
if (inactiveImage) dot.image = inactiveImage;
}
}
}
- (void)setCurrentPage:(NSInteger)page
{
[super setCurrentPage:page];
[self updateDots];
}
@end
這份實作同時處理了兩種情況:iOS 7 以上會在 dotView 的 subviews 中找到系統提供的 UIImageView 並直接替換圖片;若結構改變導致找不到,則自行補一個上去。兩條路徑都不會因為型別假設錯誤而崩潰。
另外提醒一個原範例中的小問題:activeImage 與 inactiveImage 的檔案名稱在原作者程式碼裡是對調的(activeImage 載入 inactive_page_image),使用時記得依自己的圖片命名調整,否則會出現「當前頁反而顯示未選取樣式」的怪現象。
延伸建議:如果你只是需要換掉圓點樣式,iOS 7 之後有更乾淨的做法——利用 pageIndicatorTintColor、currentPageIndicatorTintColor,或直接自製一個小元件,都比 hack UIPageControl 的私有檢視結構來得安全,也不必擔心下一個系統版本又改一次。
原始討論可參考:https://stackoverflow.com/questions/18975544/uipagecontrol-is-not-with-uiimageview-in-ios7