UIButton 点击之后改变文字颜色

默认button的颜色为灰色,点击button之后颜色变为黑色,其他button颜色不改变。

[btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
 [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
此时,点击之后没有改变效果。要加上:
btn.selected = NO;
源码贴上:
NSArray *btnArr = @[@"社区通知",@"社区活动",@"社区动态",@"社区资讯"];
    for (int i = 0; i<4; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(screenWidth/4*i, screenHeight/4+64, screenWidth/4, 40);
        btn.tag = i;
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitle:btnArr[i] forState:UIControlStateNormal];
        btn.selected = NO;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        if (i == 0) {
            [self btnDidClick:btn];
        }
    }

 
  
点击方法
-(void)btnDidClick:(id)sender{
    [_selectLabel removeFromSuperview];
    CGPoint p = {[sender tag]*screenWidth/4};
    [_scrollV setContentOffset:p animated:YES];
    
    UIButton *selectBtn = (UIButton *)sender;
    //设置button是否被选中
    for (UIButton *otherBtn in self.view.subviews) {
        if ([otherBtn isKindOfClass:[UIButton class]]) {
            if (otherBtn.tag != selectBtn.tag) {
                otherBtn.selected  = selectBtn.selected = NO;
                if (selectBtn.selected == NO) {
                    selectBtn.selected = !selectBtn.selected;
                }
            }else{
                otherBtn.selected = YES;
            }
        }
    }
    NSInteger i = selectBtn.tag;
    CGRect labelRect = CGRectMake(screenWidth/4*i+10, screenHeight/4+101, screenWidth/4-20, 3);
    _selectLabel = [[UILabel alloc]init];
    _selectLabel.frame =labelRect;
    _selectLabel.backgroundColor = [UIColor orangeColor];
    CGRect selectRect =  _selectLabel.frame;
    selectRect.origin.x = screenWidth/4*i+10;
    _selectLabel.frame = selectRect;
     [self.view addSubview:_selectLabel];
}





你可能感兴趣的:(UIButton 点击之后改变文字颜色)