Search code examples
objective-cnsbutton

Objective-C NSButton Toggle


I have search and can't find any information so I would like some help here. I am new to Xcode and objective c. I have 10 NSButtons set in Interface Builder to be Push On Push Off type. I am trying to figure out how when one of the buttons is clicked and highlighted, how do I unhightlight the other nine. I am use to Java, in java you can just make an if statement to turn off the highlight of the buttons not clicked. In IB I don't see how to send a message to the other buttons because I don't know their "names" or addresses. Can you please help me figure this out, explain it or send me to a link or video. Thank you.


Solution

  • This is what I've used in the past.

    Create an NSArray with all your buttons in it, something like:

    NSArray* buttons = @[button1, button2, button3, button4];
    

    Then create a method like this.

    - (void) toggleButtons: (id) sender {
        for (Button *item in buttons) {
            if (item == sender) {
                item.selected = !item.selected;
            } else {
                item.button.selected = NO;
            }
        }
    }
    

    Now call it from each of your button handlers:

    - (IBAction) handleButton1:(id) sender {
        [self toggleButtons:sender];
        <...rest of your code...>
    }