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

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

最重要的注意点:
(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

你可能感兴趣的:(导航条(二)下划线的移动效果)