天天看点

swift4 attributedText简单使用以及改变链接字体颜色

showTextView.delegate = self
        
        let str = showTextView.text ?? ""
        let title = "本《隐私政策》将向你说明:\n"
        let checkTotal = "你可以查看完整版"
        let redText = "隐私政策"
        
        let paragraphCenterStyle = NSMutableParagraphStyle()
        paragraphCenterStyle.alignment = .center
        
        let defaultAttr: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.hex("555555"),
            .font: UIFont.systemFont(ofSize: 14)
        ]
        let mediumFontAttr: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.hex("555555") ,
            .font: UIFont.systemFont(ofSize: 14, weight: .medium)
        ]
        let centerMediumFontAttr: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.hex("555555") ,
            .font: UIFont.systemFont(ofSize: 14, weight: .medium),
            .paragraphStyle: paragraphCenterStyle
        ]
        let redAttr: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 14, weight: .medium),
            .link: NSURL(string: "protocol://") ?? NSURL(),
            .foregroundColor: UIColor.red,
            .paragraphStyle: paragraphCenterStyle
        ]
        
        let titleText = title.toAttr(mediumFontAttr)
        let content = str.toAttr(defaultAttr)
        let check = checkTotal.toAttr(centerMediumFontAttr)
        let red = redText.toAttr(redAttr)
        let show = titleText + content + "\n" + check + red
        showTextView.linkTextAttributes = [:]
        showTextView.attributedText = show

           

要想使用自定义的链接颜色,需要在设置attributedText属性之前,把linkTextAttributes置为空。

showTextView.linkTextAttributes = [:]

showTextView.attributedText = show

实现协议:

extension PrivacyViewController: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        // 跳到隐私协议
        if URL.scheme == "protocol" {
            guard
                let host = AppConfig.config?.htmlHosts?.randomElement(),
                let url = NSURL(string: host + "/mobile/agreement.html") as URL? else {
                    return false
            }
            dismiss(animated: true){}
            let vc = AppWebViewController()
            vc.url = url
            AppDelegate.shared.navigation.push(vc)
        }
        return false
    }
}

           

参考效果:

swift4 attributedText简单使用以及改变链接字体颜色

222.png

继续阅读