2011-03-20 51 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