iOS:使用多个按钮

时间:2015-06-19 20:52:25

标签: ios select button background

我试图随机改变背景颜色作为超时效果,点击屏幕上的任何按钮。 我想用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];

}

1 个答案:

答案 0 :(得分:1)

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

- (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];
}
}
相关问题