While creating sign up page for our app, we mostly add a text beneath sign up button telling user that By signing up, you are accepting our privacy policy and terms and condition. So when user tap on highlighted area, in our case privacy policy, terms and condition, we will take user to web pages that showcased privacy policy info and similarly terms and condition for the app. In this tutorial, we will learn how to achieve a particular action when user click on particular text of UILabel.
Creating UITapGesture extension, that contains a function to detect whether user click on particular text of UILabel
Download UITapGetsure extension file from here
UITapGesture Extension
How to use UITapgesture extension
let us say, lblTermsAndConditions is your UILabel where you displayed text By signing up, you are accepting our privacy policy and terms and condition
Adding UITapGestureRecognizer to UILabel
self.lblTermsAndConditions.isUserInteractionEnabled = true | |
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(tappedOnLabel(_ :))) | |
tapgesture.numberOfTapsRequired = 1 | |
self.lblTermsAndConditions.addGestureRecognizer(tapgesture) |
UITapGesture added to UILabel
Selector for UITapGesture added to UILabel
//MARK:- tappedOnLabel | |
@objc func tappedOnLabel(_ gesture: UITapGestureRecognizer) { | |
guard let text = self.lblTermsAndConditions.text else { return } | |
let privacyPolicyRange = (text as NSString).range(of: "privacy policy") | |
let termsAndConditionRange = (text as NSString).range(of: "terms and condition") | |
if gesture.didTapAttributedTextInLabel(label: self.lblTermsAndConditions, inRange: privacyPolicyRange) { | |
print("user tapped on privacy policy text") | |
} else if gesture.didTapAttributedTextInLabel(label: self.lblTermsAndConditions, inRange: termsAndConditionRange){ | |
print("user tapped on terms and conditions text") | |
} | |
} |
Download adding selector for tapgesture added to UILabel file from here
adding selector for tapgesture added to UILabel
In above code, you can replace or create new range for the text you want to detect. Now when you run your code and tap on UILabel you will see the console will print the statements when user tapped on desired text range.