You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中用UIViewRepresentable实现HyperLink时UITextView无文本显示

解决UITextView在UIViewRepresentable中不显示文本的问题

你的代码存在几个关键问题导致UITextView无法显示文本,以下是具体修复方案:

核心问题与修复点

  1. 布局尺寸未自适应
    UITextView默认开启滚动功能,SwiftUI无法自动计算其固有内容高度,导致视图被压缩成高度为0的状态。需要添加:
textView.isScrollEnabled = false

让文本视图根据内容自动调整尺寸。

  1. 未处理URL可选值
    直接强制解包URL(string: url)!会在URL格式无效时引发崩溃,应该先判断URL是否有效再添加链接属性。

  2. 未响应参数更新
    updateUIView方法为空,当外部传入的text、url、hyperText发生变化时,文本视图不会同步更新内容,需要在该方法中重新生成富文本并赋值。

  3. 链接跳转逻辑错误
    shouldInteractWith方法中仅判断了能否打开URL,没有执行实际的跳转操作,且返回false会阻止系统处理链接,需要补充打开URL的代码。

修复后的完整代码

struct ArtieHyperLink: UIViewRepresentable {
    var url: String = ""
    var text: String = ""
    var hyperText: String = ""
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.delegate = context.coordinator
        textView.isEditable = false
        textView.isSelectable = true
        textView.isScrollEnabled = false // 关键:关闭滚动,让视图自适应高度
        textView.dataDetectorTypes = [.link]
        textView.textColor = .black
        textView.backgroundColor = .clear
        textView.textAlignment = .center
        textView.font = .systemFont(ofSize: 16)
        
        updateAttributedText(for: textView)
        return textView
    }
    
    func updateUIView(_ textView: UITextView, context: Context) {
        updateAttributedText(for: textView) // 参数变化时更新内容
    }
    
    // 抽出生成富文本的逻辑,复用代码
    private func updateAttributedText(for textView: UITextView) {
        let attributedString = NSMutableAttributedString(string: text)
        let range = (attributedString.string as NSString).range(of: hyperText)
        
        // 安全处理URL可选值
        if let url = URL(string: url), range.location != NSNotFound {
            attributedString.addAttribute(.link, value: url, range: range)
        }
        
        textView.attributedText = attributedString
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UITextViewDelegate {
        var artieHyperLink: ArtieHyperLink
        
        init(_ artieHyperLink: ArtieHyperLink) {
            self.artieHyperLink = artieHyperLink
        }
        
        func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
            // 实际执行打开URL操作
            if UIApplication.shared.canOpenURL(URL) {
                UIApplication.shared.open(URL)
            }
            return false // 返回false表示自己处理跳转,阻止系统默认行为
        }
    }
}

使用说明

调用方式保持不变:

ArtieHyperLink(url: "https://www.google.com.tr", text: "This is HyperLink test.", hyperText: "test")

内容的提问来源于stack exchange,提问作者Ufuk Köşker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:25:24