-1

I have created a custom view that is to be used as a radio button with images and text. I need to be able to load the saved selection when the controller loads. I set my listeners this way:

for button in genderButtons {
    button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(genderTapped(_:))))
}

@objc private func genderTapped(_ sender: UITapGestureRecognizer) {
    for button in genderButtons {
        button.select(sender.view! == button) // Toggles the button to display selected/deslected state.

        ...
    }
}

The problem is that I can't find a way to tell the view to select. I tried making the gesture recognizer and object, but it doesn't have any methods I can use to trigger it. The 'buttons' aren't actually buttons, they're views, so I can't send an action event.

How can I select the correct button with code?

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
Cody Harness
  • 1,116
  • 3
  • 18
  • 37
  • are you not able to find the correct view tapped? or you are not able to change the state of the view to selected? – Kamran Apr 13 '18 at 18:08
  • Instead of subclassing your buttons to inherent from `UIView`, subclass them to inherent from `UIControl` instead (which itself inherts from `UIView`). They function just like views do but controls allow you to post action updates and they're better suited to handle touch events which you can handle using methods like `touchesBegan(_:with:)`. – trndjc Apr 13 '18 at 19:04

2 Answers2

3

Just call genderTapped directly, handing it the gesture recognizer already attached to the desired "button".

For example, if thisGenderButton is the one you want to "tap", say:

if let tap = thisGenderButton.gestureRecognizers?[0] as? UITapGestureRecognizer {
    genderTapped(tap)
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
0

You can add this method in your customView like this,

Class CustomView: UIView {

    public func select(_ value: Bool) {
       self.backgroundColor = value ? .green: .red
    }
}

and then in below method you can call select for the tapped view.

@objc private func genderTapped(_ sender: UITapGestureRecognizer) {
   (sender.view as? CustomView)?.select(true)
}
Kamran
  • 14,987
  • 4
  • 33
  • 51
  • 1
    no need to add tag, You can directly use `sender.view?.select(true)` in `func genderTapped` – Ankit Jayaswal Apr 13 '18 at 19:18
  • I already have a tag. What your suggesting is what's already done. What I need to do is be able to make a specific button call the genderTapped() function when necessary. – Cody Harness Apr 13 '18 at 19:26
  • @CodyHarness Do you want a callback when a button inside a `CustomView` is tapped? – Kamran Apr 13 '18 at 19:59