NSAttributedString click event in UILabel using swift

前端 未结 7 1991
感情败类
感情败类 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:32

    Language update based on @Lindsey Scott answer :)

    Swift 4

    class ViewController: UIViewController, UITextViewDelegate {
       
        @IBOutlet weak var textView: UITextView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            let text = NSMutableAttributedString(string: "Already have an account? ")
            text.addAttribute(NSAttributedStringKey.font,
                              value: UIFont.systemFont(ofSize: 12),
                              range: NSRange(location: 0, length: text.length))
            
            let interactableText = NSMutableAttributedString(string: "Sign in!")
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: UIFont.systemFont(ofSize: 12),
                                          range: NSRange(location: 0, length: interactableText.length))
            
            // Adding the link interaction to the interactable text
            interactableText.addAttribute(NSAttributedStringKey.link,
                                          value: "SignInPseudoLink",
                                          range: NSRange(location: 0, length: interactableText.length))
            
            // Adding it all together
            text.append(interactableText)
            
            // Set the text view to contain the attributed text
            textView.attributedText = text
            
            // Disable editing, but enable selectable so that the link can be selected
            textView.isEditable = false
            textView.isSelectable = true
            textView.delegate = self
        }
        
        func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
            
            //Code to the respective action
            
            return false
        }
    }
    

提交回复
热议问题