iOS分类导航条(二)下划线的移动效果

这个是对上篇文章的优化。
上篇下划线的效果直接是消失和出现,这篇文章里面改成下划线的移动效果,不会显得突兀。

最重要的注意点:
(1)不要把下划线添加到button里面,要不然怎么着都是出现消失的效果。(千万记住)
(2)可以通过调节动画的时间看效果。

初始化的代码没有用到,没有删除,不影响。

只改动了XXTitleView.m的代码,直接上代码了:

//
//  XXHomeView.m
//  XXTableBar
//
//  Created by shine on 2016/12/26.
//  Copyright © 2016年 shine. All rights reserved.
//

#import "XXTitleView.h"
//#import "UIView+Extension.h"

@interface XXTitleView ()

//保存所有的button
@property (strong, nonatomic) NSMutableArray *titleButtons;

//titleView
@property (weak, nonatomic) UIScrollView *titleView;

//记录上一个按钮的宽度
@property(nonatomic, assign)CGFloat lastbtnW;

//记录当前选中的按钮
@property (weak, nonatomic) UIButton *currentButton;

//记录当前选中按钮的下划线
@property (strong, nonatomic) UIView *currentLine;

@end

@implementation XXTitleView
#pragma mark -- 懒加载
- (NSMutableArray *)titleButtons{

    if(_titleButtons == nil){
        _titleButtons = [NSMutableArray array];
    }
    return _titleButtons;
}

- (UIView *)currentLine{
    if (_currentLine == nil) {
        _currentLine = [[UIView alloc] init];
        _currentLine.backgroundColor = [UIColor redColor];
    }
    return _currentLine;
}

#pragma mark -- set方法
- (void)setTitleArray:(NSArray *)titleArray{
    if(_titleArray == nil){
        _titleArray = titleArray;
    }
    
    [self setupTitleView];
}

#pragma mark -- 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        //初始化界面
    }
    return self;
}

- (void)setupTitleView{
    //NSLog(@"我是setupTitleView");
    //1.创建titileView
    UIScrollView *titleView = [[UIScrollView alloc] init];
    titleView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    titleView.showsVerticalScrollIndicator = NO;
    titleView.showsHorizontalScrollIndicator = NO;
    titleView.bounces = NO;
    titleView.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:titleView];
    self.titleView = titleView;
    
    //2.创建8-10个按钮,并将其加入到titleView
    float btnMargin = 5;
    float btnX = 0;
    for (int i = 0; i < self.titleArray.count; i++) {
        
        //2.1 根据文字计算button的宽度
        NSDictionary *arributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
        NSStringDrawingOptions option = NSStringDrawingUsesFontLeading | NSStringDrawingUsesDeviceMetrics | NSStringDrawingUsesLineFragmentOrigin;
        CGSize titleSize = [self.titleArray[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:option attributes:arributes context:nil].size;
        CGFloat textW = titleSize.width + 2 * btnMargin;
        self.lastbtnW = textW;
        btnX = btnX + textW;
        //NSLog(@"btnX = %f",btnX);
        
        //2.2 创建button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        //button.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
        button.frame = CGRectMake(btnX - self.lastbtnW, 0, textW, self.frame.size.height);
        
        //2.3 设置button的文字,不要使用button.titleLabel.text,不要使用sizetofit
        [button setTitle:self.titleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        
        //2.4 添加button到视图中
        [self.titleButtons addObject:button];
        [self.titleView addSubview:button];
        
        //2.5添加button点击事件
        [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        
        //3.设置titleView的contentSize
        self.titleView.contentSize = CGSizeMake(CGRectGetMaxX(button.frame), 0);
        
        //4.程序运行时默认在第一个按钮
        if(i == 0){
            UIButton *firstBtn = self.titleButtons[i];
            self.currentButton = firstBtn;
            self.currentButton.selected = YES;
            //创建一根下划线,添加到titleView中(千万不能放在button里面,要不然没有移动的效果,而是突然消失和出现的效果)
            //线宽和选中的button一样宽,线高为3
            self.currentLine.frame = CGRectMake(0, self.currentButton.frame.size.height - 3, self.currentButton.frame.size.width, 3);
            [self.titleView addSubview:self.currentLine];
        }
    }
}


- (void)clickButton:(UIButton *)button{
    NSLog(@"%d",button.tag);

    //将之前选中的按钮的selected设置为no
    //获取之前选中按钮的宽度,为计算伸缩比例作准备
    CGFloat lastButtonW = self.currentButton.frame.size.width;
    self.currentButton.selected = NO;
    
    //将现在选中的按钮的selected设置为yes,并将此按钮赋值给当前按钮。
    button.selected = YES;
    self.currentButton = button;

    [UIView animateWithDuration:0.1 animations:^{

        CGFloat lineW = self.currentButton.frame.size.width;
        //CGFloat lineH = 3;
                //获取当前按钮的center并将其赋给下划线(有问题,从上往下掉为什么)
        CGPoint buttonCenter = self.currentButton.center;
        CGPoint lineCenter = self.currentLine.center;
        lineCenter.x = buttonCenter.x;
        self.currentLine.center = lineCenter;
        //计算伸缩的比例
        CGFloat sx = lineW / lastButtonW;
        self.currentLine.transform = CGAffineTransformScale(self.currentLine.transform, sx, 1);
    }];
    
    //获取当前按钮的x值,只有当第三种情况下才需要改变scrollview的偏移
    //1.获取到当前点击按钮的x值,加上此按钮的宽度与中心作比较,如果小于宽度的中心,将titleVIew的偏移量设置为0
    //2.获取到当前点击按钮的x值,减去此按钮的宽度与中心作比较,如果大于宽度的中心,将titleVIew的x偏移量设置为contenSize-屏幕的宽度
    //3.其他情况。按钮相对于屏幕的位移+此按钮的一半宽度与屏幕中心作对比。
    //获取当前按钮的x值
    CGFloat buttonX = CGRectGetMaxX(self.currentButton.frame) - self.currentButton.frame.size.width;
    //获取当前scrollView的x偏移量
    CGFloat offsetX = self.titleView.contentOffset.x;
    
    //取得当前按钮此时相对于屏幕的值
    CGFloat widthToScreen = buttonX - offsetX;
    
    //获取屏幕宽度的一半
    CGFloat halfWidth = [[UIScreen mainScreen] bounds].size.width * 0.5;
    
    //当前按钮的x值加上按钮的一半宽度
    CGFloat buttonXaddHalfWidth = widthToScreen + 0.5 * self.currentButton.frame.size.width;
    
    if ((buttonX + 0.5 * self.currentButton.frame.size.width) < halfWidth) {
        //button的x值+button一半的宽度小于屏幕宽度的一半
        //将titleVIew的偏移量设置为0
        [self.titleView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    else if ((self.titleView.contentSize.width - buttonX - 0.5 * self.currentButton.frame.size.width < halfWidth)){
        //button的x值-button一半的宽度大于屏幕宽度的一半
        //将titleVIew的x偏移量设置为contenSize-屏幕的宽度
        CGFloat titleViewOffsetX = self.titleView.contentSize.width - 2 * halfWidth;
        [self.titleView setContentOffset:CGPointMake(titleViewOffsetX, 0) animated:YES];
        
    }
    else{
        //相对于屏幕的宽度+按钮宽度的一半<屏幕的中心, 则向右移一点(即titleVIew的x偏移量减小)
        //相对于屏幕的宽度+按钮宽度的一半>屏幕的中心, 则向左移一点(即titleVIew的x偏移量增大)
        //改变偏移量
        CGFloat titleViewOffsetX = self.titleView.contentOffset.x - (halfWidth - buttonXaddHalfWidth);
        [self.titleView setContentOffset:CGPointMake(titleViewOffsetX, 0) animated:YES];
    }

}
@end

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

推荐阅读更多精彩内容