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