iPhone开发中UIPageControl实现自定义按钮是本文要介绍的内容,主要讲解的是来实现自定义按钮,有时候UIPageControl需要用到白色的背景,那么会导致上面的点按钮看不见或不清楚,我们可以通过继承该类重写函数来更换点按钮的图片现实 。
实现思路如下.
新建类继承UIPageControl :
@interfaceMyPageControl : UIPageControl
{
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 *)touchwithEvent:(UIEvent *)event { // 点击事件
[super endTrackingWithTouch:touch withEvent:event];
[self updateDots];
}
- (void)updateDots { //更新显示所有的点按钮
if (imagePageStateNormal || imagePageStateHighlighted)
{
NSArray *subview=self.subviews; // 获取所有子视图
for (NSIntegeri=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
MyPageControl *pageControl= [[MyPageControl alloc] initWithFrame:CGRectMake(0,0, 200, 30)];
pageControl.backgroundColor= [UIColorclearColor];
pageControl.numberOfPages=5;
pageControl.currentPage=0;
[pageControl setImagePageStateNormal:[UIImage imageNamed:@"pageControlStateNormal.png"]];
[pageControl setImagePageStateHighlighted:[UIImage imageNamed:@"pageControlStateHighlighted.png"]];
[self.view addSubview:pageControl];
[pageControl release];
原文地址:http://blog.csdn.net/scy411082514/article/details/7689624