如何在iOS中创建一个简单的复选框?

Doo*_*oom 59 iphone checkbox ios

可能重复:
IPhone应用程序中的复选框

我想创建一个带有2个值的简单复选框并保存,我该怎么做?

谢谢.

Gal*_*ank 121

是的,iOS中没有你的复选框( - :

这是我创建复选框的方法:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Run Code Online (Sandbox Code Playgroud)

现在在目标方法中执行以下操作:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}
Run Code Online (Sandbox Code Playgroud)

而已!

  • 如果你有多个按钮,你可以在你的taget方法`UIButton*btn =(UIButton*)发送者上使用它; if([btn isSelected]){[btn setSelected:NO]; } else {[btn setSelected:YES]; }` (9认同)
  • 只是一个非常非常小的评论.不要忘记字符串前的@:@"notselectedcheckbox.png". (3认同)

Jus*_*Sid 34

在iOS上有切换UI组件而不是复选框,查看UISwitch类.属性on(布尔值)可以用来确定滑块的状态以及状态的保存:这取决于你如何保存其他东西,它只是保存一个布尔值.

  • @Hiren Prajapati:为什么?如果需要获取多个布尔选择,则可以使用多个UISwitch元素,就像在主Preference应用程序中所做的那样。对于UI应该为某些情况传达“完成/未完成”状态的情况,使用UISwitch而不是选中标记的唯一罪魁祸首只是美观/具有代表性。 (2认同)