OStack程序员社区-中国程序员成长平台

标题: ios - 如何在 iOS 中创建复选框? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:09
标题: ios - 如何在 iOS 中创建复选框?

我采用了两个自定义按钮和一种方法来设置它们的选中和取消选中

在 viewdidload() 中我是这样写的..

[checkbox_01 setImage:[UIImage imageNamed"unchecked.png"] forState:UIControlStateNormal];
[checkbox_02 setImage:[UIImage imageNamed"unchecked.png"] forState:UIControlStateNormal];
isChecked_01 = NO; //declared as boolean to change check and uncheck for button one
isChecked_02 = NO; //declared as boolean to change check and uncheck for button two

在方法中

-(IBAction)checkboxOnClickUIButton *)sender {
    if (sender.tag == 1) {
        if (isChecked_01 == NO) {
            [checkbox_01 setImage:[UIImage imageNamed"checked.png"] forState:UIControlStateNormal];
            isChecked_01 = YES;
        }
        else
        {
            [checkbox_01 setImage:[UIImage imageNamed"unchecked.png"] forState:UIControlStateNormal];
            isChecked_01 = NO;
        }
    }

    if (sender.tag == 2) {
        if (isChecked_02 == NO) {
            [checkbox_02 setImage:[UIImage imageNamed"checked.png"] forState:UIControlStateNormal];
            isChecked_02 = YES;
        }
        else
        {
            [checkbox_02 setImage:[UIImage imageNamed"unchecked.png"] forState:UIControlStateNormal];
            isChecked_02 = NO;
        }
    }
}

还有其他方法可以在 ios.. 中创建复选框吗?我已经为每个复选框使用了一个 isChecked bool 值。是否有可能对整个检查列表只使用一个 bool 值.....



Best Answer-推荐答案


您可以使用 selected属性(继承自 UIControl)而不是您的 isChecked_01 和 isChecked_02:

[checkbox_01 setImage:[UIImage imageNamed"unchecked.png"] forState:UIControlStateNormal];
[checkbox_02 setImage:[UIImage imageNamed"unchecked.png"] forState:UIControlStateNormal];

[checkbox_01 setImage:[UIImage imageNamed"checked.png"] forState:UIControlStateSelected];
[checkbox_02 setImage:[UIImage imageNamed"checked.png"] forState:UIControlStateSelected];

- (IBAction)checkboxOnClickUIButton *)sender {
    sender.selected = !sender.selected;
}

关于ios - 如何在 iOS 中创建复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974554/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4