2011-03-20 40 views

回答

117

呀,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]; 

做如下操作:

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

就是这样!

+3

只是一个非常非常非常小的评论。不要忘记字符串前的@:@“notselectedcheckbox.png”。 – polyclick 2011-10-20 11:23:57

+8

以及如果你有多个按钮,你可以在你的taget方法上使用它'UIButton * btn =(UIButton *)sender; \t if([btn isSelected]){ \t \t [btn setSelected:NO]; \t} else { \t \t [btn setSelected:YES]; \t}' – andsien 2011-10-26 01:52:38

+1

您定义突出显示状态的两行不是必需的!他们只是干扰复选框(至少在iOS5中)。 :) – 2012-04-27 21:39:36

28

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

+1

我更喜欢UISwitch,因为它是原生的,优化的并且容易定制。第一个答案也很棒,但对我来说(这只是个人的先决条件),如果不需要的话,不需要重新发明车轮。 – Septronic 2016-02-27 01:14:45

+0

如果我们想允许用户选择多个选项,交换机是没有用的。 – 2017-06-30 11:25:40

+1

@Hiren Prajapati:为什么?如果您需要获取多个布尔选项,您将使用多个UISwitch元素,因为它在主Preference应用程序中完成。使用UISwitch而不是复选标记的唯一罪魁祸首就是当用户界面应该传达一个“完成/未完成”状态的情况下,在审美/代表性方面。 – valeCocoa 2017-08-08 23:01:51