借鉴文章:http://blog.csdn.net/showhilllee/article/details/8350663
找了好多文章,想找个最简单的方法来自定义pageControl,觉得这种方法是代码相对较少的,但是帖子比较古老了,里面的 updateDots 设置的为UImageView,现在xcode是跑不起来的,dug下发现原来,现在的subviews 中存的为UIView,直接上一段代码,随手写的demo没有像外界提供任何接口,纯属了解思路用
.h文件中
import <UIKit/UIKit.h>
@interface XMPageControl : UIPageControl
@end
.m文件
import "XMPageControl.h"
#define SCREEN_WITH [[UIScreen mainScreen]bounds].size.width
@implementation XMPageControl
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
return self;
}
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
[super endTrackingWithTouch:touch withEvent:event];
[self updateDots];
}
- (void)updateDots {
for (int i=0; i<self.subviews.count; ++i) {
UIView *dot = [self.subviews objectAtIndex:i];
//此处两个color可以抽出,为外界提供接口
dot.backgroundColor = i==self.currentPage ? [UIColor orangeColor]:[UIColor redColor];
}
}
/**
* 如果想实现帖子这种http://blog.csdn.net/showhilllee/article/details/8350663设置image,
* 可参考思路,在layoutSurviews中 remove掉所有的 view 替换为imageView,
* 还可设置uiview的layer根据image绘制 backgroundcolor
*/
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat space = 5.f; //space, dotW H 等可以可抽出为外界所用
CGFloat dotW = SCREEN_WITH/14.f;
CGFloat dotH = dotW/7.f;
CGFloat totalWith = (dotW+space) * self.numberOfPages;
for (int i=0; i<self.subviews.count; ++i) {
UIView *dot = [self.subviews objectAtIndex:i];
CGFloat dotX = (self.frame.size.width-totalWith)/2.f + (space+dotW)*i;
CGFloat dotY = (self.frame.size.height-dotH)/2.f;
dot.frame = CGRectMake(dotX, dotY, dotW, dotH);
}
}
- (void)setCurrentPage:(NSInteger)currentPage {
[super setCurrentPage:currentPage];
[self updateDots];
}
@end
没有提供任何的接口,用法和常规无异!
效果如图: