Suppose I have an AttributedString : \"Already have an account? Sign in!\". I am placing this String in UILabel. Now when a user clicks on \"Sign in!\", current viewControl
You need to Use UITextView
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let attribute:NSAttributedString = NSAttributedString(string: "Already have an account? Sign in!", attributes: ["Tag" : true])
textView.attributedText = attribute
let tap = UITapGestureRecognizer(target: self, action: #selector(self.textTapped(_:)))
tap.delegate = self
textView.userInteractionEnabled = true
textView.addGestureRecognizer(tap)
}
func textTapped(recognizer:UITapGestureRecognizer) {
let textView:UITextView = recognizer.view as! UITextView
// Location of the tap in text-container coordinates
let layoutManager = textView.layoutManager
var location:CGPoint = recognizer.locationInView(textView)
location.x -= textView.textContainerInset.left
location.y -= textView.textContainerInset.top
var distance:CGFloat?
// Find the character that's been tapped on
let characterIndex = layoutManager.characterIndexForPoint(location, inTextContainer: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: &distance!)
if characterIndex < textView.textStorage.length{
var range:NSRange?
let value = textView.attributedText.attribute("Tag", atIndex: characterIndex, effectiveRange: &range!)
if value {
// add your code here
}
}
}
}