點擊按鈕時改變按鈕上字體的顏色

-(void)layoutButton{

    NSArray *buttonArr = @[@"推薦", @"分類", @"廣播", @"榜單", @"主播"];

    for (int i = 0; i<5; i++) {

        self.button = [UIButton buttonWithType:UIButtonTypeSystem];

        self.button.frame = CGRectMake(202 * i * ([UIScreen mainScreen].bounds.size.width - 20 * 2) / 9, 40, ([UIScreen mainScreen].bounds.size.width - 20 * 2) / 9, 28);

        [self.button setTitle:buttonArr[i] forState:UIControlStateNormal];

        [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//設置按鈕正常時的字體顏色

        [self.button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];//設置按鈕被按下去時的字體顏色

        self.button.tag = 200 + i;

        self.button.selected = NO;//把按鈕的點擊狀態設置爲NO

        [self.button addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];

        self.button.tintColor = [UIColor colorWithRed:244 / 255.0 green:244 / 255.0 blue:244 / 255.0 alpha:1];//設置button的渲染顏色

        [self.aview addSubview:self.button];

        if (i == 0) {

            self.button.selected = YES;//設置‘推薦’的默認狀態是被選中的,即它上的字體顏色默認是紅色

        }

    }

//點擊button事件

-(void)handleButton:(UIButton *)button {

     NSInteger i = button.tag;

    button.selected = YES;

    self.isButton.selected = NO;//isbutton是設置的屬性。這裏表示上一個點擊的按鈕,把它的狀態設置成不被選中,即它的字體顏色是黑色的。

    if (i == 200) {

        button.selected = YES;//當點擊的按鈕是‘推薦’時,設置‘推薦’按鈕的狀態是被選中的,即它的字體顏色是紅色

    }else {

    UIButton *oneButton = (UIButton *)[self.aview viewWithTag:200];

    oneButton.selected = NO;//當點擊的按鈕不是‘推薦’時,設置‘推薦’按鈕的狀態是不被選中的,即它的字體顏色變成黑色。

    }

    if (button.selected == YES) {

        //button.selected = NO;

        self.isButton = button;//把當前點擊的按鈕,記錄下來,用is button接收。

    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章