所謂重寫UIPageControl類自定義分頁控件,其實就是通過重寫這個類的函數來更換點按鈕的圖片顯示。以下即爲繼承UIPageControl類的子類,主要是要分別設置正常與高亮狀態的圖片。
// CustomPageControl.h
#import <UIKit/UIKit.h> @interface CustomPageControl : UIPageControl { // 表示正常與高亮狀態的圖片
UIImage *imagePageStateNormal; UIImage *imagePageStateHighlighted; } @property (nonatomic, retain) UIImage *imagePageStateNormal; @property (nonatomic, retain) UIImage *imagePageStateHighlighted; - (id)initWithFrame:(CGRect)frame; @end
// CustomPageControl.m
#import "CustomPageControl.h" @interface CustomPageControl (private) //聲明一個私有方法,該方法不允許對象直接使用
- (void)updateDots; @end @implementation CustomPageControl @synthesize imagePageStateNormal; @synthesize imagePageStateHighlighted; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; return self; } // 設置正常狀態點按鈕的圖片
- (void)setImagePageStateNormal : (UIImage *)image { [imagePageStateHighlighted release]; imagePageStateHighlighted = [image retain]; [self updateDots]; } // 設置高亮狀態點按鈕的圖片
- (void)setImagePageStateHighlighed : (UIImage *)image { [imagePageStateNormal release]; imagePageStateNormal = [image retain]; [self updateDots]; } // 捕捉點擊事件
- (void)endTrackingWithTouch : (UITouch *)touch withEvent:(UIEvent *)event { [super endTrackingWithTouch:touch withEvent:event]; [self updateDots]; } // 更新顯示所有的點按鈕
- (void)updateDots { if(imagePageStateNormal || imagePageStateHighlighted) { NSArray *subview = self.subviews; // 獲取所有子視圖
for(NSInteger i =0; i<[subview count]; i++) { UIImageView *dot = [subview objectAtIndex:i]; dot.image = self.currentPage == i ? imagePageStateNormal : imagePageStateHighlighted; } } } - (void)dealloc { [imagePageStateNormal release], imagePageStateNormal = nil; [imagePageStateHighlighted release], imagePageStateHighlighted = nil; [super dealloc]; } @end
現在就可以用自定義的UIPageControl類來創建和初始化分頁控件
CustomPageControl *myPageControl = [[CustomPageControl alloc] initWithFrame:CGRectMake(0,0,200,30)]; myPageControl.backgroundColor = [UIColor clearColor]; myPageControl.numberOfPages = 5; myPageControl.currentPage = 0; [myPageControl setImagePageStateNormal:[UIImage imageNamed:@"normal.png"]]; [myPageControl setImagePageStateHighlighted:[UIImage imageNamed:@"highlighted.png"]]; [self.view addSubview:myPageControl]; [myPageControl release];