I am trying to use UITapGestureRecognizer to change a UIView color when the view is tapped, then back to the original white color when space outside the UIView is tapped. I can get the UIView to change colors but I cannot get it to change back to white color.
// viewDidLoad
let tapGestureRegonizer = UITapGestureRecognizer(target: self, action:
#selector(mortgagePenaltyVC.viewCellTapped(recognizer:)))
tapGestureRegonizer.numberOfTapsRequired = 1
mortgageLenerViewCell.addGestureRecognizer(tapGestureRegonizer)
@objc func viewCellTapped (recognizer: UITapGestureRecognizer){
print("label Tapped")
mortgageLenerViewCell.backgroundColor = UIColor.lightGray
}
I think you can use touchesBegan
method to get the touch outside of view like below
This code works for me...
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
guard let location = touch?.location(in: mortgageLenerViewCell) else { return }
if !labelToClick.frame.contains(location) {
print("Tapped outside the view")
mortgageLenerViewCell.backgroundColor = UIColor.white
}else {
print("Tapped inside the view")
mortgageLenerViewCell.backgroundColor = UIColor.lightGray
}
}
here labelToClick
is the label on which you want to click & mortgageLenerViewCell
is the superview of labelToClick
Feel free to ask for any query...
Thank you.