NSAttributedString click event in UILabel using swift

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

    Swift 4.2 and Xcode 11 Using TextView it's much easy

    func setupContactUsInTextView() {
        let text = NSMutableAttributedString(string: "Contact us at email ")
        text.addAttribute(NSAttributedStringKey.font,
                          value: UIFont.systemFont(ofSize: 17),
                          range: NSRange(location: 0, length: text.length))
    
        let interactableText = NSMutableAttributedString(string: "contact@abc.com")
        interactableText.addAttribute(NSAttributedStringKey.font,
                                      value: UIFont.systemFont(ofSize: 17),
                                      range: NSRange(location: 0, length: interactableText.length))
    
    
        interactableText.addAttribute(NSAttributedStringKey.link,
                                      value: "contact@abc.com",
                                      range: NSRange(location: 0, length: interactableText.length))
    
    
        text.append(interactableText)
    
    
        contactUsTextView.attributedText = text
        contactUsTextView.textAlignment = .center
        contactUsTextView.isEditable = false
        contactUsTextView.isSelectable = true
        contactUsTextView.delegate = self
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        print("open website here...")
        return false
    }
    

提交回复
热议问题