Swiftui 使用 UITextVIew 作为超链接,但无法更改文本颜色

问题描述 投票:0回答:1

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

我尝试实现 UITextView,但我只能更改链接前景色。 我添加了 textView.textColor = xxx 但它不起作用。只有我的链接颜色改变了。

    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
        }
    }
swiftui uitextview textcolor
1个回答
1
投票

这就是我的意思。使用 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
    ]
© www.soinside.com 2019 - 2024. All rights reserved.