0

I'm trying to identify the clicked radio button using the Interface builder identifier.

enter image description here

 @IBAction func text_radio_changed(_ sender: Any) {
        let button:NSButton = sender as! NSButton
        let id:String = button.accessibilityIdentifier()
        print("===========>"+id)
    }

But the console keeps printing this

===========>

There is no identifier

techno
  • 6,100
  • 16
  • 86
  • 192
  • You can connect an IBOutlet to each button, change your method signature to (_ button: NSButton)` and then `switch button { case button1: ... case button2 ... default: break }` – Leo Dabus Apr 17 '20 at 21:35
  • @LeoDabus what is 'button1' ? Identifier ? – techno Apr 18 '20 at 00:39
  • you can choose any name you want when you connect an IBOutlet to your button – Leo Dabus Apr 18 '20 at 00:48
  • @LeoDabus All radio buttons are connected to a single outlet.Only 1 is manually connected, rest is copy pasted. – techno Apr 18 '20 at 00:50
  • I don't know what you mean. If you created your button programmatically is the name of your var. If you created it using storyboard you can choose any name when connecting it to an IBOutlet – Leo Dabus Apr 18 '20 at 00:52
  • @LeoDabus Take a look https://stackoverflow.com/a/61243810/848968 – techno Apr 18 '20 at 00:53

2 Answers2

3

button.accessibilityIdentifier is the Accessibility Identity Identifier. The Identity Identifier is button.identifier.

@IBAction func text_radio_changed(_ sender: Any) {
    let button:NSButton = sender as! NSButton
    let id:String = button.identifier!.rawValue
    print("===========>"+id)
}
Willeke
  • 14,578
  • 4
  • 19
  • 47
1

On your code you are actually trying to access the accessibility identifier which is a different thing. To identify the radio button you should use tags. Set a tag for the button and then read it like this.

@IBAction func text_radio_changed(_ sender: Any) {
    let button:NSButton = sender as! NSButton
    let id:Int = button.tag
    print("===========>"+id)
}

Note: You can actually do use the accessibility id to do the same thing. Check this other similar post.

Update: The answer by "Willeke" seems better (if it works), I am used to developing for iOS and I wasn't aware there is an identifier property for NSButtons.

Nick
  • 242
  • 2
  • 12
  • I knew that tag can be used to achieve the same.But I prefer a string rather than a number – techno Apr 17 '20 at 19:25
  • You can use an enum to hold all the different values and give them string equivalents. Alternatively take a look the hyperlink in my answer with instruction on how to use the accessibility identifier that uses strings. – Nick Apr 17 '20 at 19:27