代码改变世界

转:重写UIPageControl类实现分页自定义按钮

2012-01-07 16:22  张智清  阅读(1099)  评论(0编辑  收藏  举报

所谓重写UIPageControl类自定义分页控件,其实就是通过重写这个类的函数来更换点按钮的图片显示。以下即为继承UIPageControl类的子类,主要是要分别设置正常与高亮状态的图片。

// CustomPageControl.h
#import <UIKit/UIKit.h>

@interface CustomPageControl : UIPageControl
{
// 表示正常与高亮状态的图片
UIImage *imagePageStateNormal;
UIImage *imagePageStateHighlighted;
}
@property (nonatomic, retain) UIImage *imagePageStateNormal;
@property (nonatomic, retain) UIImage *imagePageStateHighlighted;

- (id)initWithFrame:(CGRect)frame;
@end
// CustomPageControl.m
#import "CustomPageControl.h"

@interface CustomPageControl (private) //声明一个私有方法,该方法不允许对象直接使用
- (void)updateDots;
@end

@implementation CustomPageControl
@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)setImagePageStateHighlighed : (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

现在就可以用自定义的UIPageControl类来创建和初始化分页控件

CustomPageControl *myPageControl = [[CustomPageControl alloc] initWithFrame:CGRectMake(0,0,200,30)];
myPageControl.backgroundColor = [UIColor clearColor];
myPageControl.numberOfPages = 5;
myPageControl.currentPage = 0;
[myPageControl setImagePageStateNormal:[UIImage imageNamed:@"normal.png"]];
[myPageControl setImagePageStateHighlighted:[UIImage imageNamed:@"highlighted.png"]];
[self.view addSubview:myPageControl];
[myPageControl release];