有时候UIPageControl需要用到白色的背景, 那么会导致上面的点
按钮看不见或不清楚,
我们可以通过继承该类重写函数来更换点按钮的
图片现实.
实现思路如下.
新建类继承UIPageControl :
复制代码
- @interface MyPageControl : UIPageControl
- {
- UIImage *imagePageStateNormal;
- UIImage *imagePageStateHighlighted;
- }
- - (id)initWithFrame:(CGRect)frame;
- @property (nonatomic, retain) UIImage *imagePageStateNormal;
- @property (nonatomic, retain) UIImage *imagePageStateHighlighted;
- @end
|
声明了初始化该类的函数
用了两个UIImage保存两张图片, 大家知道的, UIPageCotrol的按钮分为两态, 一个是正常, 一个是高亮
接下来实现该类以及重写父类方法:
复制代码
- @interface MyPageControl(private) // 声明一个私有方法, 该方法不允许对象直接使用
- - (void)updateDots;
- @end
- @implementation MyPageControl // 实现部分
- @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)setImagePageStateHighlighted:(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
|
OK, 在添加处加入以下来实例化该对象
代码:
复制代码
- MyPageControl *pageControl = [[MyPageControl alloc] initWithFrame:CGRectMake(0,0, 200, 30)];
- pageControl.backgroundColor = [UIColor clearColor];
- pageControl.numberOfPages = 5;
- pageControl.currentPage = 0;
- [pageControl setImagePageStateNormal:[UIImage imageNamed:@"pageControlStateNormal.png"]];
- [pageControl setImagePageStateHighlighted:[UIImage imageNamed:@"pageControlStateHighlighted.png"]];
- [self.view addSubview:pageControl];
- [pageControl release];