I'm new to IOS programming, I'm displaying a view when a button is clicked, using the following code inside the button method.
@IBAction func moreButton(_ sender: Any)
{
self.helpView.isHidden = false
}
initially, the self.helpView.isHidden
is set to true in viewDidLoad
method to hide the view. Now, how can i dismiss this view by touching anywhere outside the view. From the research, i found that, it can be done by creating a transparent button that fits the whole viewController. So then by clicking on the button, we can make the view to dismiss. Can anyone give me the code in swift 3 to create such button.
Or, if there is any other better way to hide a view, it is welcomed.
I'm using Xcode 8.2, swift 3.0
Thanks in advance.
In touch began you should write like
override func touchesBegan(_ touches: Set<AnyHashable>, withEvent event: UIEvent) {
var touch: UITouch? = touches.first
//location is relative to the current view
// do something with the touched point
if touch?.view != yourView {
yourView.isHidden = true
}
}
Swift 5.1:
This should help to dismiss the view once touched outside of the view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch = touches.first
if touch?.view != self.yourView
{ self.dismiss(animated: true, completion: nil) }
}
In Swift 4
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if touch?.view == self.view {
commentsTxtView.resignFirstResponder()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With