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

Weex iOS自定义富文本组件(WXTextView.swift)无法显示内容求助

解决Weex iOS自定义富文本组件不显示内容的问题

我仔细看了你的代码,发现几个关键问题导致自定义富文本组件在Weex iOS端无法显示内容,下面一步步帮你排查修复:

1. 自定义组件未注册到Weex SDK

Weex不会自动识别你的自定义组件,你必须在App启动时把TextComponet注册为JS里用到的richText组件,否则JS中的<richText>标签无法关联到你的原生实现。

在AppDelegate的初始化方法里添加注册代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 初始化Weex SDK环境
    WXSDKEngine.initSDKEnvironment()
    // 注册自定义富文本组件
    WXSDKEngine.registerComponent("richText", with: TextComponet.self)
    return true
}

2. 富文本赋值时机与生命周期不匹配

你在init方法里初始化了attributedText,但Weex组件的属性可能会动态更新,而且loadView执行时可能attributedText还未正确赋值(或者转换失败)。正确的做法是重写updateAttributes方法,在属性初始化或更新时统一处理富文本转换,同时更新视图。

另外,你写的HTML字符串有闭合标签错误:<html><body>\(data)<body></html>里的第二个<body>应该是</body>,这会导致HTML转富文本失败,进而显示空内容。

3. UILabel的布局适配问题

你使用了label.sizeToFit(),但Weex的布局是由自身的样式系统控制的,手动调整Label大小会破坏Weex的布局逻辑,应该让Label自动适应Weex分配的布局空间,去掉sizeToFit即可。


修改后的完整代码

原生Swift组件(WXRichText.swift)

import Foundation
import WeexSDK
import UIKit

class TextComponet: WXComponent {
    private let label = UILabel()
    
    override func loadView() -> UIView {
        label.numberOfLines = 0
        label.adjustsFontSizeToFitWidth = true
        return label
    }
    
    override init(ref: String, type: String, styles: [AnyHashable : Any]?, attributes: [AnyHashable : Any]? = nil, events: [Any]?, weexInstance: WXSDKInstance) {
        super.init(ref: ref, type: type, styles: styles, attributes: attributes, events: events, weexInstance: weexInstance)
        // 初始化时处理属性
        updateAttributedText(with: attributes)
    }
    
    override func updateAttributes(_ attributes: [AnyHashable : Any]?) {
        super.updateAttributes(attributes)
        // 属性更新时重新生成富文本
        updateAttributedText(with: attributes)
        // 通知视图更新布局
        setNeedsLayout()
    }
    
    private func updateAttributedText(with attributes: [AnyHashable : Any]?) {
        guard let data = attributes?["data"] as? String else {
            label.attributedText = nil
            return
        }
        // 修复HTML闭合标签错误
        let htmlString = "<html><body>\(data)</body></html>"
        guard let attributedStr = htmlString.htmlToAttributedString else {
            print("⚠️ HTML转富文本失败")
            label.attributedText = nil
            return
        }
        label.attributedText = attributedStr
    }
}

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else {
            print("⚠️ 无法将字符串转为UTF8数据")
            return nil
        }
        do {
            return try NSAttributedString(
                data: data,
                options: [
                    NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
                    NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
                ],
                documentAttributes: nil
            )
        } catch {
            print("⚠️ HTML转换错误: \(error.localizedDescription)")
            return nil
        }
    }
    
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

JS代码(无需修改,确保属性传递正常即可)

<template>
 <div>
 <text class="message">Hi Bramma</text>
 <richText :data="data" >
 </richText>
 </div>
</template>
<script>
 export default {
 data () {
 return {
 data: '<p style="color:red">This text is normal.</p><p><b>This text is bold.</b></p>'
 }
 }
 }
</script>

额外调试提示

可以在updateAttributedText方法里添加日志,查看data是否正确从JS传递到原生,以及HTML转换是否成功,方便排查后续可能出现的问题。

内容的提问来源于stack exchange,提问作者Abhishek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:04:49