在其他地方看到下面所示的控件效果,就自己實現了一下,廢話不多說,直接上代碼:
在下面方法中創建視圖
- (void)_creatSubviews {
NSArray *array = @[@"閒置廣場",@"通知",@"個人中心",@"其他"];
//創建四個按鈕
for (int i = 0; i < array.count; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(kScreenWidth/array.count * i, 200, kScreenWidth/array.count, 50);
button.backgroundColor = [UIColor clearColor];
[button setTitle:array[i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self addSubview:button];
button.tag = i;
button.titleLabel.font = [UIFont systemFontOfSize:20];
if (i == 0) {
//按鈕選中標識視圖
_selectView = [[UIView alloc]initWithFrame:button.frame];
_selectView.backgroundColor = [UIColor orangeColor];
_selectView.layer.cornerRadius = 5.0;
[self addSubview:_selectView ];
}
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}
[self bringSubviewToFront:_selectView];
_selectView.clipsToBounds = YES; //超出範圍剪切
//創建字體顏色爲白色的label的俯視圖
_labelSuperView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
[_selectView addSubview:_labelSuperView];
//創建文字顏色爲白色的label
for (int i = 0; i < array.count; i++) {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/array.count * i, 0, kScreenWidth/array.count, 50)];
label.text = array[i];
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:20];
label.textAlignment = NSTextAlignmentCenter;
[_labelSuperView addSubview:label];
}
}
點擊按鈕時執行下面方法
- (void)buttonAction:(UIButton *)button {
CGFloat xPos = button.frame.size.width * (- button.tag);
[UIView animateWithDuration:0.5 animations:^{
_labelSuperView.frame = CGRectMake(xPos, 0, kScreenWidth, 50); //設置_labelSuperView位置
_selectView.center = button.center;
}];
}