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(_
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) }
}
You can use this method in swift 4.
add the tag number to the uiview you want to add action
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
if touches.first?.view?.tag == 10{
dismiss(animated: true, completion: nil)
super.touchesEnded(touches , with: event)
}
}
You can use touchesBegan
method for that:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.helpView.isHidden = true
}
You could create another transparent button or, your base view (assuming it's a single view below the button) can then address what you're trying to do. First, you would need to make it tappable. Then you want to handle the logic for what happens when tapped, or untapped.
Swift
override func touchesBegan(_ touches: Set<AnyHashable>, withEvent event: UIEvent) {
var touch: UITouch? = touches.first
if touch?.view != self.yourView {
self.yourView.isHidden = true
}
}
Objective C
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if(touch.view != self.yourView){
self.yourView.hidden = YES;
}
}
In Swift 4
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if touch?.view == self.view {
commentsTxtView.resignFirstResponder()
}
}