实现的效果
.h 文件
#import <UIKit/UIKit.h>
@interface YYFirstViewController : UIViewController
@end
.m 文件
#import "YYFirstViewController.h"
#import "UIView+YYExtension.h" // 引入头文件
@interface YYFirstViewController ()
@property (nonatomic, strong)UIView *indicatorView; // 指示器
@property (nonatomic, strong)UIButton *selectedBtn; //选中按钮
@end
@implementation YYFirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化顶部标题栏
[self setUpTitleView];
}
#pragma mark -初始化顶部标题栏
- (void)setUpTitleView{
CGFloat y = self.navigationController.navigationBar.height + [UIApplication sharedApplication].statusBarFrame.size.height;
UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, y, self.view.width, 35)];
// titleView.backgroundColor = [UIColor whiteColor];
// titleView.alpha = 0.8; // 会让内部所有内容半透明
// 设置颜色半透明(三种方式)
titleView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
// titleView.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.7];
// titleView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.7];
[self.view addSubview:titleView];
// 创建指示器
UIView *indicatorView = [[UIView alloc]init];
indicatorView.backgroundColor = [UIColor redColor];
indicatorView.height = 2; //(对UIView的扩展(Category))
indicatorView.y = titleView.height - 2;//(对UIView的扩展(Category))
self.indicatorView = indicatorView;
[titleView addSubview:indicatorView];
// 添加子标签
NSArray *titles= @[@"全部",
@"视频",
@"声音",
@"图片",
@"段子"];
CGFloat btnWidth = titleView.width / titles.count; //(对UIView的扩展(Category))
CGFloat btnHeight = titleView.height;
CGFloat btnY = 0.0;
for (int i = 0; i < titles.count; i ++) {
CGFloat btnX = i * btnWidth;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(btnX, btnY, btnWidth, btnHeight);
[btn setTitle:titles[i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateDisabled];
btn.titleLabel.font = [UIFont systemFontOfSize:14];
[btn addTarget:self action:@selector(titleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
[titleView addSubview:btn];
if (i == 0) {
[btn layoutIfNeeded]; // 如果不加这句话,btn 的titleLabel的宽度为0(强制刷新一次)
[self titleBtnAction:btn];
}
}
}
/**
标题栏选中
*/
- (void)titleBtnAction:(UIButton *)btn{
[UIView animateWithDuration:0.25 animations:^{
// 交换三部曲
self.selectedBtn.enabled = true;
btn.enabled = false;
self.selectedBtn = btn;
// 交换三部曲
/** 这种方法有问题
self.selectedBtn.selected = false;
btn.selected = true;
self.selectedBtn = btn;
*/
// 改变指示器
self.indicatorView.width = btn.titleLabel.width;//1.重点 2.(对UIView的扩展(Category))
self.indicatorView.centerX = btn.centerX; //(对UIView的扩展(Category))
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end