mariia
6/25/2019 - 4:46 AM

Handle links in text

//Version 1, extension
extension NSMutableAttributedString {
    
    public func setAsLink(textToFind: String, stringURL: String) -> Bool {
        let foundRange = mutableString.range(of: textToFind)
        
        if foundRange.location != NSNotFound {
            addAttribute(.link, value: stringURL, range: foundRange)
            return true
        }
        
        return false
    }
    
}


//Version 2, with ranges.
class ViewController: UIViewController {
    //Disable "editable" for textView.
    @IBOutlet weak var textView: UITextView! 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let attributedString = NSMutableAttributedString(string: "Want to play the best game ever? Try Kingdom Hearts!")
        attributedString.addAttribute(.link, value: "https://en.wikipedia.org/wiki/Kingdom_Hearts", range: NSRange(location: 37, length: 14))
        textView.attributedText = attributedString
    }

}

extension ViewController: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)
        return false
    }
    
}