一个导航条

导航栏下面添加的view会出现布局错误,解决办法先记下来。
将添加的视图移到导航栏的下面

self.edgesForExtendedLayout = UIRectEdgeNone;
self.navigationController.navigationBar.translucent = NO;//两种都可以

这种方式解决的话,注意frame的y值的设置:

XXTitleView *titleView = [[XXTitleView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];

还有一种方式,避免scrollView的自动布局

self.automaticallyAdjustsScrollViewInsets = NO;

这种方式解决,frame的y值要留一个状态栏和导航栏的距离:

XXTitleView *titleView = [[XXTitleView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 40)];

还需注意:
(1)设置button的文字,不要使用button.titleLabel.text,应该用set方法。
(2)不要使用sizetofit,容易出错(原因还没想到,这里只是提醒自己。
(3)用boundingRectWithSize方法根据文字计算button的宽度,一定记得要把button的宽度多设一点(至少多设2),不能刚刚好,要不然显示不全。

下面是显示的导航栏的demo,点击某个按钮,如果不是最靠左和最靠右,则将其显示在屏幕中间。下面加一个下划线(下划线的效果是直接出现,想优化成滑动的效果,且留作下次的任务)。主要代码如下:

AppDelegate.m文件

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] init];
    self.window.backgroundColor = [UIColor whiteColor];
    
    XXHomeViewController *homeVC = [[XXHomeViewController alloc] init];
    
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:homeVC];
    //self.window.rootViewController = homeVC;
    [self.window makeKeyAndVisible];
    return YES;
}

XXHomeViewController.m文件

#import "XXHomeViewController.h"
#import "XXTitleView.h"

@interface XXHomeViewController ()

@property (strong, nonatomic) NSArray *titleArray;

@end

@implementation XXHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"标题";
    
    //self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.titleArray = @[@"百度",@"腾讯",@"阿里巴巴",@"微博",@"美团",@"百思不得姐",@"应用宝",@"苹果",@"搞笑视频",@"小说"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    XXTitleView *titleView = [[XXTitleView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 40)];
    titleView.titleArray = self.titleArray;
    [self.view addSubview:titleView];
    
}
@end

XXTitleView.h文件

#import 

@interface XXTitleView : UIView

@property (strong, nonatomic) NSArray *titleArray;

@end

XXTitleView.m文件

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

@interface XXTitleView ()

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

//保存所有的下划线
@property (strong, nonatomic) NSMutableArray *titleLines;

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

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

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

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

- (NSMutableArray *)titleLines{
    if (_titleLines == nil) {
        _titleLines = [NSMutableArray array];
    }
    return _titleLines;
}

#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];
    titleView.delegate = self;
    [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];
        
        //创建一根下划线,添加到button中
        CGFloat lineW = titleSize.width;
        CGFloat lineH = 3;
        CGFloat lineX = 0.5 * (button.frame.size.width - lineW);
        CGFloat lineY = button.frame.size.height - lineH;
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(lineX, lineY, lineW, lineH)];
        line.tag = i;
        line.backgroundColor = [UIColor redColor];
        line.hidden = YES;
        [self.titleLines addObject:line];
        [button addSubview:line];
//        NSLog(@"button : %@",NSStringFromCGRect(button.frame));
//        NSLog(@"line : %@",NSStringFromCGRect(line.frame));
        
        
        //3.设置titleView的contentSize
        self.titleView.contentSize = CGSizeMake(CGRectGetMaxX(button.frame), 0);
    }
}


- (void)clickButton:(UIButton *)button{
    NSLog(@"%d",button.tag);
    
    //取出当前的下划线,并将其hidden设置为no
    self.currentButton.selected = NO;
    UIView *selectedLine = self.titleLines[self.currentButton.tag];
    selectedLine.hidden = YES;
    
    button.selected = YES;
    self.currentButton = button;
    UIView *currentLine = self.titleLines[self.currentButton.tag];
    currentLine.hidden = NO;
 
    
    //获取当前按钮的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

一个导航条_第1张图片
屏幕快照 2016-12-29 下午8.22.14.png

你可能感兴趣的:(一个导航条)