有时候UIPageControl需要用到白色的背景, 那么会导致上面的点按钮看不见或不清楚,
我们可以通过继承该类重写函数来更换点按钮的图片现实.
实现思路如下.
新建类继承UIPageControl :
@interface MyPageControl : UIPageControl
{
UIImage *imagePageStateNormal;
UIImage *imagePageStateHighlighted;
}
- (id)initWithFrame:(CGRect)frame;
@property (nonatomic, retain) UIImage *imagePageStateNormal;
@property (nonatomic, retain) UIImage *imagePageStateHighlighted;
@end
复制代码
声明了初始化该类的函数
用了两个UIIma
接下来实现该类以及重写父类方法:
@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];这里有点问题在休整一下:如果直接做setCurrentPage的話,圖片就會失效了,所以覆寫setCurrentPage// 覆寫setCurrentPage
- (void)setCurrentPage:(NSInteger)currentPage
{
[super setCurrentPage:currentPage];
[self updateDots];
}