Question

I have this method bellow. Is there any way I can count UISwitches which are set on? Thanks!

while (i < numberOfAnswers) {
    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
    mySwitch.tag = i;
    [_answerView addSubview:mySwitch];        
    i++;        
 }
Was it helpful?

Solution

I think that it'd be better if you keep references to switches.

NSMutableArray *switches = [NSMutableArray array]; // You can do that as property

while (i < numberOfAnswers) {
    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
    mySwitch.tag = i;
    [_answerView addSubview:mySwitch];
    i++;

    [switches addObject:mySwitch];
 }

Then later you don't have to iterate through every subview in view but you can iterate just switches array.

int count = 0;

for (UISwitch *switch in switches)
{
    if (switch.isOn)
    {
        count += 1;
    }
}

OTHER TIPS

I like Piotr's solution, but if you really just want to know how many switches are on, you can also add this line to your initialization loop:

[mySwitch addTarget:self action:@selector(switchValueDidChange:) forControlEvents:UIControlEventValueChanged];

add a property to your class:

@property (nonatomic) int onCounts

And then this method:

-(void)switchValueDidChange:(UISwitch)sender {
    self.onCounts = sender.on ? self.onCounts + 1 : self.onCounts - 1;
}

Now you can access the onCount property at any time to know how many switches are on.

Try

int count = 0;
for (UIView *subview in _answerView.subviews) {
    if ([subview isKindOfClass:[UISwitch class]]) {
        UISwitch *sw = (UISwitch*)subview;
        count += sw.isOn ? 1 : 0;
    }
}

here your code

int count = 0;
for (int i = start_switch_tag;i< numberOfAnswers;i++) {
    if (((UISwitch *)[_answerView viewWithTag:i]).isOn) count ++;
}
NSLog(@"number of switches set ON: %d", count);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top