如图
111.gif
直接上代码
@interface HHPageControl : UIView
@property(nonatomic, strong) UIColor *itemNormalColor;
@property(nonatomic, strong) UIColor *itemSelectColor;
@property(nonatomic, assign) CGFloat itemInset;
@property(nonatomic, assign) CGFloat itemHeight;
@property(nonatomic, assign) CGFloat itemSelectWidth;
@property(nonatomic, assign) CGFloat itemCornerRadius;
@property(nonatomic, assign) NSInteger numbers;
@property(nonatomic, assign) NSInteger index;
@end
@implementation HHPageControl
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupUI];
}
return self;
}
- (void)setupUI {
// 默认配置
self.itemNormalColor = [UIColor blackColor];
self.itemSelectColor = [UIColor whiteColor];
self.itemInset = 9;
self.itemHeight = 15;
self.itemSelectWidth = 36;
self.itemCornerRadius = self.itemHeight * 0.5;
}
- (void)setNumbers:(NSInteger)numbers {
_numbers = numbers;
[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
UIView *lastView = nil;
for (int i = 0; i < numbers; i++) {
UIView *view = [[UIView alloc] init];
view.backgroundColor = i == self.index?self.itemSelectColor:self.itemNormalColor;
view.layer.cornerRadius = self.itemCornerRadius;
[self addSubview:view];
view.width = i == self.index?self.itemSelectWidth:self.itemHeight;
view.height = self.itemHeight;
view.y = 0;
view.x = 0;
if (lastView) {
view.x = CGRectGetMaxX(lastView.frame)+self.itemInset;
}
NSLog(@"view = %@",NSStringFromCGRect(view.frame));
lastView = view;
}
self.width = CGRectGetMaxX(lastView.frame);
self.height = self.itemHeight;
}
- (void)setIndex:(NSInteger)index {
_index = index;
NSArray *views = self.subviews;
if (views.count) {
UIView *lastView = nil;
for (int i = 0; i < views.count; i++) {
UIView *view = views[i];
view.backgroundColor = self.itemNormalColor;
view.width = self.itemHeight;
if (index == i) {
view.backgroundColor = self.itemSelectColor;
view.width = self.itemSelectWidth;
}
if (lastView) {
view.x = CGRectGetMaxX(lastView.frame)+self.itemInset;
} else {
view.x = 0;
}
lastView = view;
}
}
}
@end
如何使用
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
self.view.backgroundColor = [UIColor blueColor];
HHPageControl *pc = [[HHPageControl alloc] init];
pc.backgroundColor = [UIColor redColor];
pc.itemNormalColor = [UIColor yellowColor];
pc.itemSelectColor = [UIColor greenColor];
pc.itemInset = 20;
pc.itemHeight = 20;
pc.itemSelectWidth = 50;
pc.itemCornerRadius = 10;
pc.numbers = 4;
pc.y = 200;
pc.x = (screenW-pc.width)/2;
[self.view addSubview:pc];
self.pc = pc;
}
static NSInteger scrollIndex = 0;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
scrollIndex++;
if (scrollIndex>3) {
scrollIndex = 0;
}
self.pc.index = scrollIndex;
}
网友评论