2015-06-19 81 views
0

我想随机更改背景颜色作为超时效果屏幕上的任意按钮都被点击。 我想用开/关UIButton来控制这种效果。 点击ChangeColorButton只记录“关”从不“开”。不知道该怎么办?感谢大家!!iOS:使用多个按钮更改背景颜色

编辑的代码到目前为止! 在.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

因为你不是从任何地方改变按钮

- (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 
    } 
} 

的选择现在调用此函数来改变颜色​​

- (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]; 
} 
} 
+0

感谢souvickcse!当添加这些线是有效的。我还加了一个! to!sender.selected。现在问题是ChangeColorButton不会“关闭” –

+0

你可以更新你的最新代码吗? – souvickcse

+0

我将在原始端口上发布代码,谢谢!更新了上面的代码。完全黑客攻击周围的东西。非常感谢您的帮助! –