我试图随机更改背景颜色,因为随着时间的推移,屏幕上的任何按钮都会被点击。 我想用 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];
}
}
关于iOS:使用多个按钮更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947098/