如何为许多复选框缩短代码?

时间:2016-05-19 18:10:36

标签: objective-c

你好我正在制作应用程序,其中我有很多chekbox按钮。坏的是我的代码太长了。我为每个按钮写(如果逻辑)我实际上不喜欢。我想要使代码更短。任何人帮助我?我的代码是这样的:(检查是布尔值)

- (IBAction)firstBoxButton:(id)sender {
    if(!checked)
    {
        [firstBox setImage:[UIImage imageNamed:@"unchecked_checkbox.png"] forState:UIControlStateNormal];
        checked = YES;
    }  else
            if (checked)
            {
                [firstBox setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
                checked = NO;

            }


}
- (IBAction)secondBoxButton:(id)sender {
    if(!checked)
    {
        [secondBox setImage:[UIImage imageNamed:@"unchecked_checkbox.png"] forState:UIControlStateNormal];
        checked = YES;
    }  else
        if (checked)
        {
            [secondBox setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
            checked = NO;

        }

1 个答案:

答案 0 :(得分:0)

这样做:

创建一个像这样的新方法:

- (IBAction)anyBoxButton:(id)sender {
UIButton *anyButton = sender;
if(!checked)
{
[anyButton setImage:[UIImage imageNamed:@"unchecked_checkbox.png"] forState:UIControlStateNormal];
                checked = YES;
            }  else
            if (checked)
            {
            [anyButton setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
             checked = NO;
 }
}

然后在你的xib中将按钮firstBoxButton和secondBoxButton的动作添加到上面创建的方法中。它应该工作。