所谓重写UIPageControl类自定义分页控件,其实就是通过重写这个类的函数来更换点按钮的图片显示。以下即为继承UIPageControl类的子类,主要是要分别设置正常与高亮状态的图片。
// CustomPageControl.h
#import <UIKit/UIKit.h> @interface CustomPageControl : UIPageControl { // 表示正常与高亮状态的图片
UIImage *p_w_picpathPageStateNormal; UIImage *p_w_picpathPageStateHighlighted; } @property (nonatomic, retain) UIImage *p_w_picpathPageStateNormal; @property (nonatomic, retain) UIImage *p_w_picpathPageStateHighlighted; - (id)initWithFrame:(CGRect)frame; @end
// CustomPageControl.m
#import "CustomPageControl.h" @interface CustomPageControl (private) //声明一个私有方法,该方法不允许对象直接使用
- (void)updateDots; @end @implementation CustomPageControl @synthesize p_w_picpathPageStateNormal; @synthesize p_w_picpathPageStateHighlighted; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; return self; } // 设置正常状态点按钮的图片
- (void)setImagePageStateNormal : (UIImage *)p_w_picpath { [p_w_picpathPageStateHighlighted release]; p_w_picpathPageStateHighlighted = [p_w_picpath retain]; [self updateDots]; } // 设置高亮状态点按钮的图片
- (void)setImagePageStateHighlighed : (UIImage *)p_w_picpath { [p_w_picpathPageStateNormal release]; p_w_picpathPageStateNormal = [p_w_picpath retain]; [self updateDots]; } // 捕捉点击事件
- (void)endTrackingWithTouch : (UITouch *)touch withEvent:(UIEvent *)event { [super endTrackingWithTouch:touch withEvent:event]; [self updateDots]; } // 更新显示所有的点按钮
- (void)updateDots { if(p_w_picpathPageStateNormal || p_w_picpathPageStateHighlighted) { NSArray *subview = self.subviews; // 获取所有子视图
for(NSInteger i =0; i<[subview count]; i++) { UIImageView *dot = [subview objectAtIndex:i]; dot.p_w_picpath = self.currentPage == i ? p_w_picpathPageStateNormal : p_w_picpathPageStateHighlighted; } } } - (void)dealloc { [p_w_picpathPageStateNormal release], p_w_picpathPageStateNormal = nil; [p_w_picpathPageStateHighlighted release], p_w_picpathPageStateHighlighted = 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 p_w_picpathNamed:@"normal.png"]]; [myPageControl setImagePageStateHighlighted:[UIImage p_w_picpathNamed:@"highlighted.png"]]; [self.view addSubview:myPageControl]; [myPageControl release];
转载于:https://blog.51cto.com/rongbaohong/948103