NSAttributedString click event in UILabel using swift

前端 未结 7 1984
感情败类
感情败类 2020-12-29 13:49

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

7条回答
  •  天涯浪人
    2020-12-29 14:24

    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
            }
        }
    }
    }
    

提交回复
热议问题