实现自定义分段控件
- 相关属性声明
@interface HXSegmentControl()
//标题数组
@property (nonatomic , strong)NSArray *titleArray;
//按钮数组
@property (nonatomic , strong)NSMutableArray *buttonArray;
//选中的按钮的index
@property (nonatomic , assign)NSInteger selectedIndex;
@property (nonatomic , assign)CGFloat buttonWidth;
//按钮底部的选中标志
@property (nonatomic , weak)UIView *buttonIndicator;
//分割线 (阴影效果)
@property (nonatomic , weak)UIView *separatorLine;
@end
- 封装初始化类方法。调用初始化方法传入参数:需要设定的整个控件的frame 以及 每个分段标签上的标题数组。
+ (instancetype)segmentControlWithFrame:(CGRect)frame titleArray:(NSArray *)titleArray{
HXSegmentControl *segCtrl = [[HXSegmentControl alloc]initWithFrame:frame titleArray:titleArray];
return segCtrl;
}
- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSArray *)titleArray{
if (self = [super initWithFrame:frame]) {
//控件背景颜色默认为白色,按钮不设置背景颜色(默认透明)
self.backgroundColor = [UIColor whiteColor];
self.titleArray = titleArray;
self.buttonArray = [NSMutableArray arrayWithCapacity:titleArray.count];
[self setupButtonArray];
[self setupSeparatorLine];
}
return self;
}
- 自定义分段控件,用按钮来实现每一个分段,底部的分段选中标识用一个uiview实现。用在初始化方法里面传进来的标题数组来设置分段按钮上的文字,其余的比如字号、颜色等属性则在代码中给定默认值。
//把btn添加上
- (void)setupButtonArray{
NSInteger titleNumber = self.titleArray.count;
self.buttonWidth = self.frame.size.width / titleNumber;
//根据标题数组中的元素个数创建对应按钮
for (int i = 0; i < titleNumber ; i ++) {
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(i * self.buttonWidth, 0, self.buttonWidth, self.frame.size.height)];
btn.tag = i + 100;//tag从100之后开始设置
[btn setTitle:self.titleArray[i] forState:UIControlStateNormal];
[btn setTitle:self.titleArray[i] forState:UIControlStateSelected];
//按钮选中、非选中 默认颜色:黑色 红色
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
//按钮默认字号 14
btn.titleLabel.font = [UIFont systemFontOfSize:16.0];
[btn addTarget:self action:@selector(selectedChange:) forControlEvents:UIControlEventTouchUpInside];
[self.buttonArray addObject:btn];
[self addSubview:btn];
//默认选中第一个&创建按钮底部选中标志
if (i == 0) {
UIView *buttonIndicator = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 2.5, self.buttonWidth, 2)];//底部分割线高0.5
//选中标志默认颜色为红色
buttonIndicator.backgroundColor = [UIColor redColor];
_buttonIndicator = buttonIndicator;
[self addSubview:_buttonIndicator];
[btn setSelected:YES];//默认选中第一个
self.selectedIndex = 0;
}
}
}
//底部分割线
- (void)setupSeparatorLine{
UIView *separatorLine = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 0.5, self.frame.size.width, 0.5)];
_separatorLine = separatorLine;
_separatorLine.backgroundColor = [UIColor colorWithRed:0.78 green:0.78 blue:0.8 alpha:1.0];
[self addSubview:_separatorLine];
}
给按钮动作绑定方法。每个分段在选中、非选中情况下外观样式的变化可以通过按钮自身实现(设置不同state下title\titlecolor等),但按钮底部的分段选中标识则需要通过按钮方法实现,改变选中标识的frame来移动标识的位置。
分段控件下方一般有对应的内容视图(一般是一个scrollview),滑动scrollView切换页面时也需要切换分段按钮,这里把按钮的绑定方法分为两个方法,第一个方法在主动点击按钮时触发,第二个方法被第一个方法调用,也可在scrollview切换页面时调用。
//点击按钮触发,切换按钮时候的按钮动画
- (void)selectedChange:(UIButton *)selectedBtn{
[self selectBtn:(selectedBtn.tag-100)];
}
- (void)selectBtn:(NSInteger)newIndex{
//先判断点击的按钮和上次点击的是不是同一个
if (self.selectedIndex == newIndex) {
return;
}
UIButton *lastBtn = (UIButton *)self.buttonArray[self.selectedIndex];
lastBtn.selected = NO;
UIButton *newBtn = (UIButton *)self.buttonArray[newIndex];
newBtn.selected = YES;
[UIView animateWithDuration:0.2 animations:^{
[self.buttonIndicator setFrame:CGRectMake(newIndex * self.buttonWidth,self.frame.size.height-2.5, self.buttonWidth, 2)];
}];
self.selectedIndex = newIndex;
[self.delegate selectedIndexChange:self selectedIndex:self.selectedIndex];
}
由于自定义分段控件中,只会在自身各按钮之间切换,不会引起scrollview的内容视图切换。这里定义协议,让添加分段控件的控制器vc实现协议方法,从而切换scrollview内容视图。
@class HXSegmentControl;
@protocol HXSegmentControlDelegate< NSObject>
@required
//点击按钮 切换页面
-(void)selectedIndexChange:(HXSegmentControl*)SegmentControl selectedIndex:(NSInteger)index;
@end
- 设置自定义分段控件外观属性的方法。在初始化方法中已经设置过默认的控件外观样式,如果不想使用默认样式,可以用这个方法设置非选中、选中时的按钮文字颜色、文字字号大小、底部选中标识的颜色以及整个控件的背景颜色。每个参数传入为空的则依旧使用对应属性的默认设置。
- (void)titleColor:(UIColor *)titleColor selectedTitleColor:(UIColor *)selectedTitleColor titleFontSize:(CGFloat)fontSize indicatorColor:(UIColor *)indicatorColor segBackgroundColor:(UIColor *)backgroundColor{
for (UIButton *btn in self.buttonArray) {
if (titleColor != nil) {
[btn setTitleColor:titleColor forState:UIControlStateNormal];
}
if (selectedTitleColor != nil) {
[btn setTitleColor:selectedTitleColor forState:UIControlStateSelected];
}
if (fontSize > 0) {
btn.titleLabel.font = [UIFont systemFontOfSize:fontSize];
}
}
if (indicatorColor != nil) {
self.buttonIndicator.backgroundColor = indicatorColor;
}
if (backgroundColor != nil) {
self.backgroundColor = backgroundColor;
}
}
- 在滑动分段控件下方的scrollview内容视图时,按钮底部的选中标识 随界面的拖拽而滑动,这样就不会在scrollview滑动停止之后底部选中标识的位置才突然改变。
- (void)animateIndicator:(CGFloat)rate{
CGRect newFrame = self.buttonIndicator.frame;
newFrame.origin.x = self.selectedIndex * self.buttonWidth + rate * self.buttonWidth;
self.buttonIndicator.frame = newFrame;
}
使用
视图控制器中使用。
#import "Masonry.h"
#import "HXSegmentControl.h"
#define screenWidth CGRectGetWidth([UIScreen mainScreen].bounds)
#define screenHeight CGRectGetHeight([UIScreen mainScreen].bounds)
@interface ProductDetailPageTwo ()<UIScrollViewDelegate,HXSegmentControlDelegate>
@property (nonatomic ,weak)HXSegmentControl *subSegmentCtrl;
@property (nonatomic ,weak)UIScrollView *scrollView;
@property (nonatomic ,assign)CGFloat segmentHeight;
@property (nonatomic ,strong)NSArray *controllersArray;//子控制器数组
@property (nonatomic ,strong)NSArray *titleArray; //标题数组
@property (nonatomic ,assign)CGFloat lastOffsetX;//scrollview内容切换后的x偏移
@end
- 控制器初始化方法
//初始化方法。参数1:子控制器数组 参数2:自定义分段控件的分段标题文字数组
+ (instancetype)initWithControllersArray:(NSArray *)controllersArray titleArray:(NSArray *)titleArray{
return [[self alloc]initWithControllersArray:controllersArray titleArray:(NSArray *)titleArray];
}
- (instancetype)initWithControllersArray:(NSArray *)controllersArray titleArray:(NSArray *)titleArray{
if(self = [super init]){
self.controllersArray = controllersArray;
self.titleArray = titleArray;
}
return self;
}
对于scrollview每个“页面”对应的视图,这里使用childViewController子控制器来组织,每个“页面”对应一个子控制器,再把vc.view添加到scrollview。这样做比使用addsubview来把每个“页面”上的控件都全部直接添加到scrollview上要好。原因:
苹果新的API增加了addChildViewController方法,并且希望我们在使用addSubview时,同时调用[self addChildViewController:child]方法将sub view对应的viewController也加到当前ViewController的管理中。
对于那些当前暂时不需要显示的subview,只通过addChildViewController把subViewController加进去;需要显示时再调用transitionFromViewController方法。将其添加进入底层的ViewController中。
这样做的好处:
1.无疑,对页面中的逻辑更加分明了。相应的View对应相应的ViewController。
2.当某个子View没有显示时,将不会被Load,减少了内存的使用。
3.当内存紧张时,没有Load的View将被首先释放,优化了程序的内存释放机制。
//初始化子控制器
- (void)setupChildViewControllers{
for (UIViewController *vc in self.controllersArray) {
[self addChildViewController:vc];
}
}
- 添加自定义分段控件、scrollview
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self initViews];
[self setupChildViewControllers];
}
- (void)initViews{
[self setupHXSegment];
[self setupScrollView];
}
//创建自定义分段控件
- (void)setupHXSegment{
self.segmentHeight = 40;
//创建自定义分段控件
HXSegmentControl *subSegmentCtrl = [HXSegmentControl segmentControlWithFrame:CGRectMake(0, 0, 180, self.segmentHeight) titleArray:self.titleArray];
[subSegmentCtrl titleColor:colorYellow selectedTitleColor:colorBrown titleFontSize:18.0 indicatorColor:colorBrown segBackgroundColor:[UIColor whiteColor]];
_subSegmentCtrl = subSegmentCtrl;
CGPoint newCenter = self.subSegmentCtrl.center;
newCenter.x = self.view.center.x;
self.subSegmentCtrl.center = newCenter;
_subSegmentCtrl.delegate = self;
[self.view addSubview:_subSegmentCtrl];
UIView *separatorLine = [[UIView alloc]init];//因为我在这里设置的自定义分段控件的宽度不等于屏宽,需要补一条底部分割线给它
separatorLine.backgroundColor = [UIColor colorWithRed:0.78 green:0.78 blue:0.8 alpha:1.0];
[self.view addSubview:separatorLine];
__weak typeof(self)weakself = self;
[separatorLine mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(weakself.view.frame.size.width, 0.5));
make.centerX.equalTo(weakself.view.mas_centerX);
make.bottom.equalTo(subSegmentCtrl.mas_bottom);
}];
}
//创建scrollview
- (void)setupScrollView {
UIScrollView *scrollView = [[UIScrollView alloc]init];
_scrollView = scrollView;
_scrollView.bounces = NO;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.pagingEnabled = YES;
_scrollView.contentSize = CGSizeMake(screenWidth * 2, 0);
_scrollView.delegate = self;
[self.view addSubview:_scrollView];
__weak typeof(self)weakself = self;
[_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.bottom.equalTo(weakself.view);
make.top.equalTo(_subSegmentCtrl.mas_bottom);
}];
[self.view updateConstraintsIfNeeded];
[self.view layoutIfNeeded];
//push进来默认选中第一个 添加第一个子控制器的view
UIViewController *pageIntroductionVC = self.controllersArray[0];
pageIntroductionVC.view.frame = CGRectMake(0, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
[_scrollView addSubview:pageIntroductionVC.view];
self.lastOffsetX = _scrollView.contentOffset.x;
}
- 一些代理方法
#pragma mark HXSegmentControlDelegate
//切换页面。点击分段按钮切换页面or滑动scrollview切换都会调用到这个方法
-(void)selectedIndexChange:(HXSegmentControl*)SegmentControl selectedIndex:(NSInteger)index{
CGPoint offset = self.scrollView.contentOffset;
offset.x = index * self.scrollView.frame.size.width;
[self.scrollView setContentOffset:offset animated:YES];
self.lastOffsetX = offset.x;
}
#pragma mark UIScrollViewDelegate
//计算此次scrollview滑动的距离deltaOffsetx,然后与“一页”宽度算出“比率”,自定义分段控件中的底部选中标识也要对应滑动相同“比率”距离。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat deltaOffsetx = scrollView.contentOffset.x - self.lastOffsetX;
CGFloat rate = deltaOffsetx / self.scrollView.frame.size.width;
[self.subSegmentCtrl animateIndicator:rate];
}
//滚动完毕就会调用,如果不是人为拖拽scrollView导致滚动完毕,才会调用这个方法.由setContentOffset:animated: 或者 scrollRectToVisible:animated: 方法触发
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
int index = scrollView.contentOffset.x / _scrollView.frame.size.width;
UIViewController *willShowChildVc = self.controllersArray[index];
// 如果这个子控制器的view已经添加过了,就直接返回
if (willShowChildVc.isViewLoaded) return;
willShowChildVc.view.frame = CGRectMake(scrollView.contentOffset.x, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
[scrollView addSubview:willShowChildVc.view];
}
//滚动完毕就会调用.如果是人为拖拽scrollView导致滚动完毕,才会调用这个方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
self.lastOffsetX = scrollView.contentOffset.x;
NSInteger pageNum = scrollView.contentOffset.x / _scrollView.frame.size.width;
//拖拽滑动切换页面 切换至segment对应的某项
[self.subSegmentCtrl selectBtn:pageNum];
// 添加子控制器的view
[self scrollViewDidEndScrollingAnimation:scrollView];
}
在这里,只有第一个子控制器是一开始(scrollview创建的时候)就添加到scrollview中显示出来的。其余的子控制器,在对应得“页面”滑动出来之后才加载显示出来。
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
方法
滚动完毕就会调用,如果不是人为拖拽scrollView导致滚动完毕,才会调用这个方法,也即是由setContentOffset:animated: 或者 scrollRectToVisible:animated: 方法触发。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
滚动完毕就会调用.如果是人为拖拽scrollView导致滚动完毕,才会调用这个方法。
使用demo:
NSMutableArray *testArray = [NSMutableArray array];
for (int i = 0; i < 2; i++) {
ProductIntroduction *vc = [[ProductIntroduction alloc]init];//一个随机创建背景颜色的vc
[testArray addObject:vc];
}
ProductDetailPageTwo *test2 = [ProductDetailPageTwo initWithControllersArray:testArray titleArray:@[@"商品简介",@"参数表"]];
ps:使用alloc init一个控制器不会调用到它的viewDidLoad方法,viewDidLoad在视图显示加载的时候才会调用。
实现效果
更新:初始化部分的改进。参考HMSegmentedControl。http://www.jianshu.com/p/229056b55f44
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self commonInit];
}
return self;
}
- (instancetype)initWithTitleArray:(NSArray *)titleArray{
if (self = [super initWithFrame:CGRectZero]) {
[self commonInit];
self.titleArray = titleArray;
}
return self;
}
- (void)commonInit{
self.backgroundColor = [UIColor whiteColor];
UIView *separatorLine = [[UIView alloc]init];
_separatorLine = separatorLine;
_separatorLine.backgroundColor = [UIColor colorWithRed:0.78 green:0.78 blue:0.8 alpha:1.0];
[self addSubview:_separatorLine];
UIView *buttonIndicator = [[UIView alloc]init];
buttonIndicator.backgroundColor = [UIColor redColor];
_buttonIndicator = buttonIndicator;
[self addSubview:_buttonIndicator];
}
- (void)setTitleArray:(NSArray *)titleArray{
_titleArray = titleArray;
NSInteger titleNumber = _titleArray.count;
self.buttonArray = [NSMutableArray arrayWithCapacity:titleNumber];
for (int i = 0; i < titleNumber ; i ++){
UIButton *btn = [[UIButton alloc]init];
btn.tag = i + 100;
[btn setTitle:self.titleArray[i] forState:UIControlStateNormal];
[btn setTitle:self.titleArray[i] forState:UIControlStateSelected];
//按钮选中、非选中 默认颜色:黑色 红色
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
btn.titleLabel.font = fontSize16;
[btn addTarget:self action:@selector(selectedChange:) forControlEvents:UIControlEventTouchUpInside];
[self.buttonArray addObject:btn];
[self addSubview:btn];
}
[self setNeedsLayout];
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
[self updateSeg];
}
- (void)layoutSubviews{
[self updateSeg];
}
- (void)updateSeg{
self.separatorLine.frame = CGRectMake(0, self.frame.size.height - 0.5, self.frame.size.width, 0.5);
NSInteger titleNumber = self.titleArray.count;
self.buttonWidth = self.frame.size.width / titleNumber;
for (int i = 0; i < titleNumber ; i ++){
[self.buttonArray[i] setFrame:CGRectMake(i * self.buttonWidth, 0, self.buttonWidth, self.frame.size.height)];
CGFloat stringWidth = [self sizeWithString:(NSString *)self.titleArray[i] font:fontSize16 maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)].width;
self.buttonWidth = MAX(stringWidth, self.buttonWidth);
}
[self.buttonArray[0] setSelected:YES];
self.buttonIndicator.frame = CGRectMake(0, self.frame.size.height - 2.5, self.buttonWidth, 2);
self.selectedIndex = 0;
}
- (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
{
NSDictionary *dict = @{NSFontAttributeName : font};
CGSize size = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
return size;
}