How to pass a UIView on UIButton as a parameter on click event

580 views Asked by At

I generated a multiple UIButton and UIView using loop, the problem is, I want that generated UIView to be hidden when the generated UIButton was clicked,

The question is, how can I pass the UIView on a UIButton click event so that the system knows what UIView will going to be hidden

This is my code that generate UIButtons and UIViews

for (key, value) in myStringsArray {
     let myButton = UIButton()
     let myView = UIView()

     panelButton.tag = value
     panelButton.addTarget(self, action: #selector(onMyButtonClick), for: .touchUpInside)
}

The only data that I can pass on .tag was Int

And this is my onMyButtonClick function that listen on click event of the UIButton

@objc func onMyButtonClick (sender: UIButton) {
     print(sender.tag)
}

What I want to do is to have a click listener function that is working like this

func clickMe (view: UIView, isOpen: Bool) {
     view.isHidden = isOpen
}
1

There are 1 answers

0
Keshu R. On BEST ANSWER

You can assign the button and the view the same tag.

then you can find the view by tag and hide it.

@objc func onMyButtonClick (sender: UIButton) {
     print(sender.tag)
     if let foundView = view.viewWithTag(sender.tag) {
        foundView.isHidden = true
    }
}