iOS: 使用多个按钮更改背景颜色

iOS: change background color using multiple buttons

我正在尝试随机更改背景颜色,因为随着时间的推移,屏幕上的任何按钮都被点击了。 我想用 On/Off UIButton 控制这种效果。 点击 ChangeColorButton 只会记录“关闭”而不是“打开”。不知道该怎么办?谢谢大家!!

到目前为止已编辑代码!! 在 .h

@property(nonatomic,readwrite) BOOL shouldChangeColor;

in .m
- (IBAction)ChangeColorButton:(UIButton*)sender {

   // self.shouldChangeColor = !sender.selected;
   sender.selected = !sender.selected;
    if(sender.selected)
    {
        NSLog(@"Switch is ON");
        //Make it off now
      //  sender.selected=NO;
   //    self.shouldChangeColor=TRUE;



    }
    else

        NSLog(@"Switch is OFF");
    //Make it on now
   // sender.selected=YES;
    self.shouldChangeColor=TRUE;

        }

- (void)randomColor{
    int r = arc4random() % 255;
    int g = arc4random() % 255;
    int b = arc4random() % 255;

    UIColor *color = [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0];

    [self.view setBackgroundColor:color];

}

因为您没有更改按钮的选择

- (IBAction)ChangeColorButton:(UIButton*)sender {
    //self.shouldChangeColor = sender.selected;
    sender.selected = !sender.selected; //If you do this
    if(sender.selected)
   {
      self.shouldChangeColor=YES;
      NSLog(@"Switch is ON");
      //Make it off now
      //sender.selected=NO; You Don't have to do this
      [self randomColor];//If you want to change the color when switch is on

   }
    else{
      self.shouldChangeColor=NO;
      NSLog(@"Switch is OFF");
      //Make it on now
      //sender.selected=YES; You Don't have to do this
      [self.view setBackgroundColor:[UIColor blackcolor]];//Check the syntax
    }
}

现在从任何地方调用这个函数来改变颜色[self randomColor];

- (void)randomColor{
if(self.shouldChangeColor){


int r = arc4random() % 255;
int g = arc4random() % 255;
int b = arc4random() % 255;

UIColor *color = [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0];

[self.view setBackgroundColor:color];
}
}