您的位置:首页 > 移动开发

常见新闻App顶部菜单标签栏

2016-07-11 11:50 791 查看


这是我们常见的新闻类App,点击顶部菜单切换内容。

1.构建顶部菜单栏

/**
*  设置顶部的标签栏
*/
- (void)setupTitlesView
{
// 标签栏整体
UIView *titlesView = [[UIView alloc] init];
titlesView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
titlesView.width = self.view.width;
titlesView.height = 35;
titlesView.y = 64;
[self.view addSubview:titlesView];

// 底部红色指示器
UIView *indicatorView = [[UIView alloc] init];
indicatorView.backgroundColor = [UIColor redColor];
indicatorView.height = 2;
indicatorView.y = titlesView.height - indicatorView.height;
[titlesView addSubview:indicatorView];
self.indicatorView = indicatorView;

// 内部子标签
NSArray *titles = @[@"全部 ",@"视频",@"声音",@"图片",@"段子"];
CGFloat height = titlesView.height;
CGFloat width = titlesView.width / titles.count;

for (NSInteger i=0; i<titles.count; i++) {
UIButton *button = [[UIButton alloc] init];
button.height = height;
button.width = width;
button.x = i * button.width;
[button setTitle:titles[i] forState:UIControlStateNormal];
[button layoutIfNeeded]; // 强制布局(强制更新子控件的frame)
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateDisabled];
button.titleLabel.font = [UIFont systemFontOfSize:14];
[button addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
[titlesView addSubview:button];

// 默认点击了第一个按钮
if (i == 0) {
[self titleClick:button];
}
}
}


分析:大的UIView内部,包含了若干菜单(按钮UIButton),另外还有一个View来做 指示器。

/**
*  标签底部红色指示器
*/
@property(nonatomic,weak)UIView *indicatorView;


2.点击了菜单要做的事情

点击按钮都会调用
titleClick:
这个方法

/**
*  点击了标签栏里的按钮
*/
- (void)titleClick:(UIButton *)button
{
// 修改按钮的状态
self.selectedButton.enabled = YES;
button.enabled = NO;
self.selectedButton = button;

// 动画
[UIView animateWithDuration:.025 animations:^{
self.indicatorView.width = button.titleLabel.width;
self.indicatorView.centerX = button.centerX;
}];
}


最后效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: