代码改变世界

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

  张智清  阅读(1100)  评论(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];




 

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示