Swiftui 使用 UITextVIew 进行超链接但无法更改文本颜色

Swiftui using UITextVIew for hyperlink but can't change text color

我正在尝试在 swiftui 中使用 UITextView 来显示其中包含 hyperlinks 的文本。文本和 link 应该使用相同的颜色,除了 link 有下划线。

我尝试实现 UITextView,但我只设法更改了 link 前景色。 我添加了 textView.textColor = xxx 但它没有用。只有我 link 的颜色变了。

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
    
        textView.delegate = context.coordinator
        textView.isEditable = false
        textView.font = font
        textView.autocapitalizationType = .sentences
        textView.textColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.5)
        textView.isSelectable = true
        textView.isUserInteractionEnabled = true
        textView.backgroundColor = .clear
        textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        textView.frame = textView.frame.integral
    
        return textView
    }


   func updateUIView(_ uiView: UITextView, context: Context) {
        let style = NSMutableParagraphStyle()
        let attributedOriginalText = NSMutableAttributedString(string: text)
    
        for (hyperLink, urlString) in hyperLinks {
            let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
            let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
            attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
            attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
        }
    
        uiView.linkTextAttributes = [
            .underlineStyle : NSUnderlineStyle.single.rawValue,
            .foregroundColor: UIColor(red: 255, green: 255, blue: 255, alpha: 0.5)
        ]
    
        uiView.attributedText = attributedOriginalText
    
        // COMPUTE HEIGHT FOR CONTENT
        let width = uiView.frame.size.width
        let newSize = uiView.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))
    
        DispatchQueue.main.async {
            self.dynamicHeight = newSize.height
        }
    }

这就是我的意思。使用 Xcode 13.3 / iOS 15.4

测试

*红色用于提高可见度

func updateUIView(_ uiView: UITextView, context: Context) {
    let attributedOriginalText = NSMutableAttributedString(string: text)

    for (urlString, hyperLink) in links {
        let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
        attributedOriginalText.addAttribute(.link, value: urlString, range: linkRange)
    }

    let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
    attributedOriginalText.addAttribute(.foregroundColor, value: UIColor.red, range: fullRange)

    uiView.attributedText = attributedOriginalText
    uiView.linkTextAttributes = [
        .underlineStyle : NSUnderlineStyle.single.rawValue,
        .foregroundColor: UIColor.red
    ]