Swift Tutorial: How to perform action when user click on particular text of UILabel
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 tutotial, we will learn how to achieve a particular action when user tap on certain part of UILabel's text.
Creating UITapGesture extension, that contains a function to detect wether user tap on desired text or not
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)
Download adding UITapGesture to UILabel file from here
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 if user tapped on desired text range.
NOTE:- Post originally taken from my original blog post at Swift Tutorial: How to perform action when user click on particular text of UILabel
Hii…can u give code for when we tap particular part of label it should take into next screen
Will it work if content width is less than label size?
Yes it will as it checks the range of text.
hi bro,
fo this article do we have objective c code please.i need objective c code for this many thanks
Sorry i don’t have objective c code
Use swift extension in your objective project