顶部标签的实现

实现的效果如下

我们要完成的效果有以下特点:

1.背景图是一个半透明的背景

2.在被选中时文字颜色变为红色,文字下面也有一个红色的指示器

3.在刚进入这个页面时,默认选中第一个

虽然可以使用xib进行设计,但是太繁琐,不如直接用代码来的简单

    //自定义顶部背景图
    UIView *topVC = [[UIView alloc] init];
    topVC.y += 64;
    topVC.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    topVC.width = self.view.width;
    topVC.height = 50;
    [self.view addSubview:topVC];

topVC的y值加上导航器和状态栏的高度

先添加两个属性,用于后面的引用

@interface DDZEssenceViewController ()
/** 红色指示器 */
@property (nonatomic,assign) UIView *indicator;

/** 上一个选中的按钮 */
@property (nonatomic,assign) UIButton *lastBtn;
@end

将红色指示器添加到视图中

    //在按钮下方添加一条红色的view
    UIView *indicator = [[UIView alloc] init];
    indicator.height = 2;
    indicator.y = topVC.height - indicator.height;
    [indicator setBackgroundColor:[UIColor redColor]];
    [topVC addSubview:indicator];
    self.indicator = indicator;

对顶部标签上的内容进行详细设计

    NSArray *arrName = @[@"全部",@"视频",@"声音",@"图片",@"段子"];
    //添加按钮
    CGFloat height = topVC.height;
    CGFloat width = self.view.width/5;
    for (NSInteger i = 0; i < 5; i++) {
        UIButton *btn = [[UIButton alloc] init];
        btn.width = width;
        btn.height = height;
        btn.x += i * btn.width;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateDisabled];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn setTitle:arrName[i] forState:UIControlStateNormal];
        [btn layoutIfNeeded];//立即布局
        
        //添加点击事件
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [topVC addSubview:btn];
        
        //默认选中第一个
        if (i == 0) {
            [self btnClick:btn];
        }
    }

切换按钮改变指示器的位置

//切换按钮事件
- (void)btnClick:(UIButton *)btn {
    //将上一个按钮取消激活
    self.lastBtn.enabled = YES;
    btn.enabled = NO;
    self.lastBtn = btn;
    
    [UIView animateWithDuration:0.25 animations:^{
        //获取红色指示器,更改指示器的位置
        self.indicator.width = btn.titleLabel.width;
        self.indicator.centerX = btn.centerX;
    }];
    
}
原文地址:https://www.cnblogs.com/langji/p/5472769.html