Create tap-able “links” in the NSAttributedString of a UILabel?

前端 未结 30 3033
半阙折子戏
半阙折子戏 2020-11-22 02:07

I have been searching this for hours but I\'ve failed. I probably don\'t even know what I should be looking for.

Many applications have text and in this text are web

30条回答
  •  醉梦人生
    2020-11-22 03:09

    Worked in Swift 3, pasting the entire code here

        //****Make sure the textview 'Selectable' = checked, and 'Editable = Unchecked'
    
    import UIKit
    
    class ViewController: UIViewController, UITextViewDelegate {
    
        @IBOutlet var theNewTextView: UITextView!
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //****textview = Selectable = checked, and Editable = Unchecked
    
            theNewTextView.delegate = self
    
            let theString = NSMutableAttributedString(string: "Agree to Terms")
            let theRange = theString.mutableString.range(of: "Terms")
    
            theString.addAttribute(NSLinkAttributeName, value: "ContactUs://", range: theRange)
    
            let theAttribute = [NSForegroundColorAttributeName: UIColor.blue, NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue] as [String : Any]
    
            theNewTextView.linkTextAttributes = theAttribute
    
         theNewTextView.attributedText = theString             
    
    theString.setAttributes(theAttribute, range: theRange)
    
        }
    
        func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    
            if (URL.scheme?.hasPrefix("ContactUs://"))! {
    
                return false //interaction not allowed
            }
    
            //*** Set storyboard id same as VC name
            self.navigationController!.pushViewController((self.storyboard?.instantiateViewController(withIdentifier: "TheLastViewController"))! as UIViewController, animated: true)
    
            return true
        }
    
    }
    

提交回复
热议问题