Hyperlinks in a UITextView

后端 未结 5 1164
無奈伤痛
無奈伤痛 2020-12-01 16:18

I am trying to create a UITextView with a hyperlink so that when the user clicks on the link, they are taken to safari to open the we

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 17:02

    Swift 3, iOS10 , Xcode 9

    @sikhapol's answer is really nice if you knew exactly the words you want to parse like "word dictionary" some how

    it's all about the string it self that displayed in UITextView

    My solution is based the text rendering if you make the UITextView render an html tags you may use href tag

    Here is some Code references you may use

    first you need to configure UITextView from interface builder or form code to

    1. Selectable
    2. Data detectores

    Note : do not make the textview editable

    Interface builder

    programmatically

             let htmlData = NSString(string: "go to google and search for it").data(using: String.Encoding.unicode.rawValue)
    
    
            let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
            yourUIViewView.isSelectable = true
            yourUIViewView.dataDetectorTypes = .link
            yourUIViewView.attributedText = attributedString
            yourUIViewView.delegate = self
    

    for the UITextViewDelegate

        func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        
           // check for the url string for performing your own custom actions here
          let urlString = URL.absoluteString
        
           // Return NO if you don't want iOS to open the link
            return true
         }
    

提交回复
热议问题