swiftswift5nsattributedstringnsmutableattributedstring

How to push view controller on click of HyperLink in Swift 5


Hi I have to push a viewController on click of HyperLink. I have NSMutableAttributedString text. that attributed text have two hyperlink examples GoToHomeScreen and aboutUs both are hyperLink on click of aboutUs need to open a link which is working fine

    let attributesString = NSMutableAttributedString(string: "GoToHomeScreen for know more about app and for info aboutUs ")
    attributesString.addAttribute(.link, value: "https://apple.com/aboutUs", range: NSRange(location: 50, length: 7))
    textFields.isEditable = false
    textFields.delegate = self
    textFields.attributedText = attributesString

to open aboutUs working fine but how can we push a view controller on click of GoToHomeScreen

Note:- I am using UITextView to perform it, I can't use button


Solution

  • You need to add also a link for GoToHomeScreen.

    attributesString.addAttribute(.link, value: "myApp://GoToHomeScreen", range: ...)
    

    Since you have already set the delegate, implements textView(_:shouldInteractWith:in:interaction:):

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    
        if URL.absoluteString == "myApp://GoToHomeScreen" {
            pushHomeScreenVC()
            return false
        }
        return true
    }