1. 程式人生 > >UIButton 點選之後改變文字顏色

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];
}