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

标签 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];

}

最佳答案

因为你没有改变按钮的选择

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

相关文章:

ios - 为什么我的自定义 UITableViewCell 宽度在初始加载时不正确?

ios - CNContact 最后修改日期和联系人已更改

WHERE 子句中的 mysql SUM()

javascript - 动态添加的按钮不起作用

ios - 如何在 iOS 中以编程方式设置系统音量

iphone - 如何在 iphone .plist 文件中选择多行?

sql - Derby Select over 子查询不起作用

search - 没有搜索框按钮可以吗?

delphi - 如何创建带有下拉菜单的按钮?

ios - 核心数据 : annotation: Failed to load optimized model at path 'Users/~/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileProto.omo'