點擊button 字體跟着改變顏色


利用for循環創建5個button,其中對這個五個button一定要賦上tag值 ,因為下面的點擊操作我們要用到;

看for循環的代碼:

for (int i=0; i < 5; i++) {
        UIButton *button = [[UIButton alloc] init];
        button.frame = CGRectMake(10 + 60*i, 100, 50, 40);
        button.tag = 100 + i;
        [button setTitle:[NSString stringWithFormat:@"button%d",i] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor lightGrayColor]];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }

在click:點擊方法中有  UIButton *btn = (UIButton *)[self.view viewWithTag:100+i] 這么一行代碼,是根據tag值獲取對應for循環中的某個button;

代碼如下:

 - (void)click:(UIButton *)sender {
    for (int i=0; i < 5; i++) {
        UIButton *btn = (UIButton *)[self.view viewWithTag:100+i];
        if (sender.tag - 100 == i) {
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [btn setBackgroundColor:[UIColor purpleColor]];

        }else{
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setBackgroundColor:[UIColor lightGrayColor]];

        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM