How to hide a custom view when there was a click outside this view

So I do not want to use tap recognizer for detecting where the touch was (this approach is massive cause I have to handle it in controller).

I know that we can hide keyboard when resignFirstResponder().

How can I hide my own view (just call private func in it class) using only class of that view?

Replies

You could try the following:


- In IB, change the class of the global view from UIView to UIControl (that's possible as UIControl is a subclass of UIView)

- create an IBAction

@IBAction functapOnView(_ sender: UIControl) {

myCustomView.isHidden = true

}

- Connect the global view (now an UIConbtrol) to this IBAction


When you tap in the view, it will hide the custom view

Good way, but I do not want that other view control my custom one. Is there any other way a custom view is responsible for itself?

Custom view can only handle the events that occur within itself ! And it is not just an "other" view, it is the parent view that contains the custom one.


So you are looking for something a bit contradictory.

Unless you mean that you do not want to reference directly the view in another view.


Then you can use notification.

First, define the name of the Notification in an extension:

extension Notification.Name {
    public static let kHideCustom = Notification.Name("hideCustom")
}


Make customView subscribe to the notification, in viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(hideMe), name: .kHideCustom, object: nil)


declare the func in customView

@objc func hideMe() {
     self.isHidden = true
}


In the parent view, just post a notification instead of acting directly on the customView

@IBAction functapOnView(_ sender: UIControl) {
    NotificationCenter.default.post(name: .kHideCustom, object: self)
}