UIPageControl实现自定义按钮
UIPageControl实现自定义按钮
有时候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的按钮分为两态, 一个是正常, 一个是高亮
接下来实现该类以及重写父类方法:
@interfaceMyPageControl(private) // 声明一个私有方法, 该方法不允许对象直接使用
- (void)updateDots;
@end
@implementation MyPageControl //实现部分
@synthesize imagePageStateNormal;
@synthesize imagePageStateHighlighted;
- (id)initWithFrame:(CGRect)frame { // 初始化
self = [superinitWithFrame:frame];
return self;
}
- (void)setImagePageStateNormal:(UIImage*)image { // 设置正常状态点按钮的图片
[imagePageStateNormalrelease];
imagePageStateNormal= [image retain];
[self updateDots];
}
-(void)setImagePageStateHighlighted:(UIImage *)image { // 设置高亮状态点按钮图片
[imagePageStateHighlightedrelease];
imagePageStateHighlighted= [image retain];
[self updateDots];
}
- (void)endTrackingWithTouch:(UITouch*)touch withEvent:(UIEvent *)event { // 点击事件
[superendTrackingWithTouch: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 { // 释放内存
[imagePageStateNormalrelease], imagePageStateNormal = nil;
[imagePageStateHighlightedrelease], imagePageStateHighlighted = nil;
[super dealloc];
}
@end
OK, 在添加处加入以下来实例化该对象代码:
MyPageControl *pageControl =[[MyPageControl alloc] initWithFrame:CGRectMake(0,0, 200, 30)];
pageControl.backgroundColor = [UIColorclearColor];
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[pageControlsetImagePageStateNormal:[UIImageimageNamed:@"pageControlStateNormal.png"]];
[pageControl setImagePageStateHighlighted:[UIImageimageNamed:@"pageControlStateHighlighted.png"]];
[self.view addSubview:pageControl];
[pageControl release];