iOS 自定义分段控制器

最近做项目时遇到一些问题,就是项目里原有分段控制器的适用范围有些局限,虽然网上也有很多分段控制器的demo,但自己写的,可控性和项目适用性自己能很明白,所以我专门封装这样一个分段控制器,解决不同场景下的功能需求。

首先,介绍一下分段控制器,相信大家也都见过这样的场景


image.png

好,看到上图大家应该心里或多或少知道接下来要干的事了,我们一步一步分析如何封装一个好的分段控制器:
1.满足可配置多个子控制器
2.可配置菜单栏各个属性,如字体大小颜色等
3.指示条可配置
4.最好能扩展菜单栏,如最多展示5个,多于5个可左右滑动
5.点击和滑动到某一界面,要知道这是哪个界面

列出来需求,要实现也变得简单了许多:
我们在.h里写出可配置的属性,并写好确定当前是哪个界面的代理

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@protocol SYPageControlIndexDelegate <NSObject>

@optional

-(void)pageIndexDidChange:(NSUInteger)index;

@end

@interface SYPageControlView : UIView<UIScrollViewDelegate>

//设置菜单栏高度
@property (nonatomic,assign) NSInteger             btnViewHeight;  

//设置按钮下划线宽度
@property (nonatomic,assign) NSInteger             indicatorWidth;     //默认50,我们最好设置一下
//设置按钮下划线高度(默认1)
@property (nonatomic,assign) NSInteger             indicatorHeight;
//设置最大菜单展示个数,菜单多于最大则可滑动 (默认是childVCs的个数)
@property (nonatomic,assign) NSInteger             maxMenuCount;

@property (nonatomic,weak) id <SYPageControlIndexDelegate> delegate;

/**
 当前选中标题索引,默认0
 */
@property (nonatomic, assign) NSInteger selectIndex;

/**
 标题字体大小,默认15
 */
@property (nonatomic, strong) UIFont *titleFont;

/**
 标题选中字体大小,默认15
 */
@property (nonatomic, strong) UIFont *titleSelectFont;

/**
 标题正常颜色,默认black
 */
@property (nonatomic, strong) UIColor *titleNormalColor;

/**
 标题选中颜色,默认red
 */
@property (nonatomic, strong) UIColor *titleSelectColor;

/**
 指示器颜色,默认与titleSelectColor一样(注:如不需要,可设置透明色,也可内部去掉这个控件)
 */
@property (nonatomic, strong) UIColor *indicatorColor;


-(instancetype)initWithFrame:(CGRect)frame controllertitles:(NSArray *)titles childViewControllers:(NSArray *)childVCs delegate:(id <SYPageControlIndexDelegate>)delegate;


@end

然后我们在.m实现里实现我们这些功能

1.内部扩展一些属性和View以便使用
@interface SYPageControlView ()
{
    UIButton *_seletedBtn;
    float menuBtnWidth;
    NSMutableArray *titleBtnArr;
}
@property (nonatomic,strong) UIScrollView          *pageScroll;  //内容
@property (nonatomic,copy)   NSArray               *viewControllers;
@property (nonatomic,strong) UIView                *indicatorView;
@property (nonatomic,strong) UIScrollView          *btnView;   //可滑动的
@property (nonatomic,copy)   NSArray               *titleArray;


@end
2.实现初始化方法
-(instancetype)initWithFrame:(CGRect)frame controllertitles:(NSArray *)titles childViewControllers:(NSArray *)childVCs delegate:(id <SYPageControlIndexDelegate>)delegate{
    
    self = [super initWithFrame:frame];
    if (self) {
        self.titleArray = titles;
        self.viewControllers = childVCs;
        self.delegate = delegate;
        
        self.maxMenuCount = childVCs.count;
        menuBtnWidth = self.width/childVCs.count;
        
        //设置默认属性
        [self initWithProperty];
        //创建子视图
        [self createSubViews];
        
    }
    return self;
}
3.设置默认属性和创建子视图
//初始化默认属性值
- (void)initWithProperty
{
    self.selectIndex = 0;
    self.titleNormalColor = [UIColor blackColor];
    self.titleSelectColor = [UIColor redColor];
    self.titleFont = [UIFont systemFontOfSize:15];
    self.indicatorWidth = 50;
    self.indicatorHeight = 1;
    self.indicatorColor = self.titleSelectColor;
    self.titleSelectFont = self.titleFont;
    self.btnViewHeight = 42;
    
}

-(void)createSubViews{
    //1.头部titles
    _btnView = [[UIScrollView alloc]init];
    _btnView.frame = CGRectMake(0,0,SCREEN_WIDTH,self.btnViewHeight);
    _btnView.showsHorizontalScrollIndicator = NO;
    _btnView.backgroundColor = [UIColor whiteColor];
    _btnView.contentSize = CGSizeMake(menuBtnWidth*self.titleArray.count, self.btnViewHeight);
    [self addSubview:_btnView];
    
    //2.标题按钮
    titleBtnArr = [[NSMutableArray alloc]init];
    for (int i = 0; i < self.titleArray.count; i++)  {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i+10;
        [btn setTitle:self.titleArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
        btn.titleLabel.font = self.titleFont;
        
        btn.frame = CGRectMake(menuBtnWidth*i, 0, menuBtnWidth, self.btnViewHeight);
        [_btnView addSubview:btn];
        
        if (i==self.selectIndex) {
            _seletedBtn = btn;
            _seletedBtn.titleLabel.font = self.titleSelectFont;
            [_seletedBtn setTitleColor:self.titleSelectColor forState:UIControlStateNormal];
        }
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleBtnArr addObject:btn];
    }
    
    //3.下划线
    self.indicatorView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.indicatorWidth, self.indicatorHeight)];
    self.indicatorView.backgroundColor = self.indicatorColor;
    self.indicatorView.center = CGPointMake(menuBtnWidth/2, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
    [_btnView addSubview:self.indicatorView];
    
    
    //4.内容VC
    self.pageScroll = [[UIScrollView alloc] init];
    self.pageScroll.delegate = self;
    self.pageScroll.pagingEnabled = YES;
    self.pageScroll.bounces = NO;
    self.pageScroll.frame = CGRectMake(0,self.btnViewHeight, self.width, self.height - self.btnViewHeight);
    self.pageScroll.showsHorizontalScrollIndicator = NO;
    self.pageScroll.contentSize = CGSizeMake(self.width*self.viewControllers.count, self.pageScroll.height);
    self.pageScroll.contentOffset = CGPointMake(self.width*self.selectIndex, 0); //根据默认index设置偏移量
    [self addSubview:self.pageScroll];
    
    for (int i = 0; i<self.viewControllers.count; i++) {
        UIViewController *vc = self.viewControllers[i];
        vc.view.frame = CGRectMake(i*self.width, 0, self.width, self.pageScroll.height);
        [self.pageScroll addSubview:vc.view];
    }
    
}

设置默认属性没什么好说的,创建子视图里有几点需要注意,一是标题按钮的创建,二是设置指示器的位置,三是配置多个内容的控制器视图,仔细看代码,逻辑其实也很简单明了

4.实现按钮点击事件和视图滑动事件
#pragma mark - 事件
-(void)btnClick:(UIButton *)sender{
    
    if (_seletedBtn==sender) {
        return;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageIndexDidChange:)]) {
        [self.delegate pageIndexDidChange:sender.tag-10];
    }
    
    for (UIButton *btn in titleBtnArr) {
        btn.titleLabel.font = self.titleFont;
        [btn setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        self.indicatorView.center = CGPointMake(sender.center.x, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
        
        //想点击没有动画就把这个移到下面
        self.pageScroll.contentOffset = CGPointMake((sender.tag-10)*self.width, 0);
        [self.pageScroll setContentOffset:CGPointMake((sender.tag-10)*self.width, 0) animated:NO];
    }];
    
    sender.titleLabel.font = self.titleSelectFont;
    [sender setTitleColor:self.titleSelectColor forState:UIControlStateNormal];
    _seletedBtn = sender;
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    float index = scrollView.contentOffset.x/scrollView.frame.size.width;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageIndexDidChange:)]) {
        [self.delegate pageIndexDidChange:index];
    }
    
    UIButton *btn = (UIButton *)[self.btnView viewWithTag:index+10];
    if (_seletedBtn != btn) {
        [UIView animateWithDuration:0.3 animations:^{
            self.indicatorView.center = CGPointMake(btn.center.x, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
        }];
        
        _seletedBtn.titleLabel.font = self.titleFont;
        [_seletedBtn setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
        
        _seletedBtn = btn;
        
        _seletedBtn.titleLabel.font = self.titleSelectFont;
        [_seletedBtn setTitleColor:self.titleSelectColor forState:UIControlStateNormal];
    }
    
}

我们在内部处理了界面偏移和按钮状态更改,如外面有代理,也会将当前第几个页面的index回调给代理,外部逻辑处理会变得很简单

5.个性配置,即设置属性更改UI

我们实现属性的set方法,在set方法内部更改UI

#pragma mark - set方法
-(void)setBtnViewHeight:(NSInteger)btnViewHeight{
    _btnViewHeight = btnViewHeight;
    
    for (UIButton *btn in titleBtnArr) {
        btn.height = self.btnViewHeight;
    }
    _btnView.contentSize = CGSizeMake(menuBtnWidth*self.titleArray.count, btnViewHeight);
    self.indicatorView.center = CGPointMake(_seletedBtn.center.x, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
    self.pageScroll.frame = CGRectMake(0,self.btnViewHeight, self.width, self.height - self.btnViewHeight);
    for (int i = 0; i<self.viewControllers.count; i++) {
        UIViewController *vc = self.viewControllers[i];
        vc.view.frame = CGRectMake(i*self.width, 0, self.width, self.pageScroll.height);
    }

}

-(void)setTitleNormalColor:(UIColor *)titleNormalColor{
    _titleNormalColor = titleNormalColor;
    
    for (UIButton *btn in titleBtnArr) {
        [btn setTitleColor:titleNormalColor forState:UIControlStateNormal];
    }
    
    [_seletedBtn setTitleColor:self.titleSelectColor forState:UIControlStateNormal];
}

-(void)setTitleSelectColor:(UIColor *)titleSelectColor{
    _titleSelectColor = titleSelectColor;
    
    [_seletedBtn setTitleColor:titleSelectColor forState:UIControlStateNormal];
}

-(void)setTitleFont:(UIFont *)titleFont{
    _titleFont = titleFont;
    
    for (UIButton *btn in titleBtnArr) {
        btn.titleLabel.font = titleFont;
    }
 
    _seletedBtn.titleLabel.font = self.titleSelectFont;
}

-(void)setTitleSelectFont:(UIFont *)titleSelectFont{
    _titleSelectFont = titleSelectFont;
    
    _seletedBtn.titleLabel.font = titleSelectFont;
}

-(void)setSelectIndex:(NSInteger)selectIndex{
    _selectIndex = selectIndex;
    
    self.pageScroll.contentOffset = CGPointMake(self.width*selectIndex, 0);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageIndexDidChange:)]) {
        [self.delegate pageIndexDidChange:selectIndex];
    }
    UIButton *btn = (UIButton *)[self.btnView viewWithTag:selectIndex+10];
    if (_seletedBtn != btn) {
        [UIView animateWithDuration:0.3 animations:^{
            self.indicatorView.center = CGPointMake(btn.center.x, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
        }];
        
        _seletedBtn.titleLabel.font = self.titleFont;
        [_seletedBtn setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
        
        _seletedBtn = btn;
        
        _seletedBtn.titleLabel.font = self.titleSelectFont;
        [_seletedBtn setTitleColor:self.titleSelectColor forState:UIControlStateNormal];
    }
    
}

-(void)setIndicatorColor:(UIColor *)indicatorColor{
    _indicatorColor = indicatorColor;
    
    self.indicatorView.backgroundColor = indicatorColor;
}

-(void)setIndicatorWidth:(NSInteger)indicatorWidth{
    _indicatorWidth = indicatorWidth;
    
    self.indicatorView.frame = CGRectMake(0, 0, indicatorWidth, self.indicatorHeight);
    self.indicatorView.center = CGPointMake(_seletedBtn.center.x, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
}

-(void)setIndicatorHeight:(NSInteger)indicatorHeight{
    _indicatorHeight = indicatorHeight;
    
    self.indicatorView.frame = CGRectMake(0, 0, self.indicatorWidth, indicatorHeight);
    self.indicatorView.center = CGPointMake(_seletedBtn.center.x, self.btnViewHeight-self.indicatorHeight/2-1);//底部留1
}

-(void)setMaxMenuCount:(NSInteger)maxMenuCount{
    _maxMenuCount = maxMenuCount;
    
    if (self.titleArray.count>maxMenuCount) {
        menuBtnWidth = self.width/maxMenuCount;
        _btnView.contentSize = CGSizeMake(menuBtnWidth*self.titleArray.count, self.btnViewHeight);
        for (int i=0; i<titleBtnArr.count; i++) {
            UIButton *btn = titleBtnArr[i];
            btn.frame = CGRectMake(menuBtnWidth*i, 0, menuBtnWidth, self.btnViewHeight);
        }
    }
}

到此,自定义分段控制器就已经封装完了,我们来测试一下

    NSArray *titles = @[@"First",@"Second",@"Third"];
    
    FirstViewController *firstVC = [[FirstViewController alloc]init];
    SecondViewController *secondVC = [[SecondViewController alloc]init];
    ThirdViewController *thirdVC = [[ThirdViewController alloc]init];
    NSArray *controllers = @[firstVC,secondVC,thirdVC];
    
    SYPageControlView *pageControlView = [[SYPageControlView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) controllertitles:titles childViewControllers:controllers delegate:self];
    [self.view addSubview:pageControlView];
image.png

再修改属性来测试:

    pageControlView.maxMenuCount = 2;
    pageControlView.selectIndex = 1;
    pageControlView.titleSelectFont = [UIFont systemFontOfSize:17];
    pageControlView.titleNormalColor = [UIColor grayColor];
    pageControlView.titleSelectColor = [UIColor brownColor];
    pageControlView.indicatorWidth = SCREEN_WIDTH/2;
    pageControlView.indicatorColor = [UIColor greenColor];
image.png

属性已经全部生效,头部菜单2个并且可滑动。

注:以上代码就是按顺序来的所有代码,其中用到了一个UIView的扩展文件,可直接访问UIView的left、width等属性。布局也使用frame,大家能更清楚逻辑。
如果使用还不方便,可以去github上下载代码,也欢迎大家提出建议:
https://github.com/qingmomo/SYPageControlView

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335