UITextView设置文本超链接

private lazy var googleAccountView: UITextView = {
        let textView = UITextView()
        textView.isEditable = true
        textView.isScrollEnabled = false
        textView.delegate = self
        textView.backgroundColor = .clear
        textView.textContainerInset = .zero
        textView.textContainer.lineFragmentPadding = 0.0
        let string = "You can unlink anytime at Google Account."
        let tipString = "Google Account."
        let font = UIFont.systemFont(ofSize: 12)

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 3
        let prefixAttributedText = NSMutableAttributedString(string: string, attributes: [.font: font, .foregroundColor: UIColor.black, .paragraphStyle: paragraphStyle])
        let suffixAttributedText = NSMutableAttributedString(string: tipString, attributes: [.link: ClickJumpType.googleAccount.rawValue, .underlineStyle: NSUnderlineStyle.single.rawValue])
        textView.linkTextAttributes = [.foregroundColor: UIColor(hex: 0x007DFF),
                                       .underlineColor: UIColor(hex: 0x007DFF),
                                       .font: font]
        prefixAttributedText.append(suffixAttributedText)
        textView.attributedText = prefixAttributedText
        return textView
    }()
  • 禁用Textview的复制剪切等操作isEditable设置为true, 同时textViewShouldBeginEditing返回false
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { 
        return false
    }

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        let type = URL.absoluteString
        return true
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容