简体   繁体   中英

Only allow selection of one UIButton

I have three UIButtons subclasses (RadioBox)s. I am trying to make it so that only one of the three RadioBoxes can be selected at once. To do so, I have two delegate methods; radioSelectedState and radioUnselectedState. Respectively, the methods are called upon selection and deselection of the RadioBox. Unfortunately, my code so far allows only one button to be selected at once, but if I deselect the currently selected button, the button deselects rather than stays the same state.

Please can you tell me where I am going wrong?

Thanks in advanced.

- (void) radioSelectedState:(RadioBox *) rb {

    if (selectedRadios == nil) {
        selectedRadios = [[NSMutableArray alloc] init];
   }

    if ([selectedRadios count] == 0) {
        [selectedRadios addObject:rb];
    }

    else if ([selectedRadios count] == 1 && ![selectedRadios containsObject:rb] ) {
        [(RadioBox *) [selectedRadios objectAtIndex:0] setState:RadioBoxStateUnselected];

        [selectedRadios removeObjectAtIndex:0];

        [selectedRadios addObject:rb];

    }

    else if ([selectedRadios count] == 1 && [selectedRadios containsObject:rb]) {
        return;
    }

}

- (void) radioUnselectedState:(RadioBox *) rb {

    if ([selectedRadios count] == 1) {
        return;
    }

    [selectedRadios removeObject:rb];

}

You could easily keep your RadioBox objects inside an NSArray and loop through it every time one is selected, making sure every other gets deselected.

Something like:

// This assumes you have your RadioBox objects inside an NSArray named radioBoxArray
- (void)radioBoxTapped:(RadioBox *)rb {
    for (RadioBox * box in radioBoxArray) {
        [box setSelected:NO];
    }

    [rb setSelected:YES];
}

Add a new method to your protocol

- (BOOL)radioCanUnselect:(RadioBox *)radioBox;

Call this before doing any unselecting, the controller just replies YES / NO and then you respond accordingly.

You could also do the same the other way

- (BOOL)radioCanSelect:(RadioBox *)radioBox;

and add rules for how many are allowed to be selected at once

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM