WEEX - iOS上的RichText组件

时间:2018-06-01 11:43:25

标签: richtext weex

我正在通过扩展WXComponent在Weex中创建一个Richtext(WXTextView.swift)视图组件。 Richtext组件目前在weex iOS sdk中不可用。

这是我的WXRichText.swift示例代码

    import Foundation
    import WeexSDK
    import UIKit

    class TextComponet: WXComponent {

    var attributedText: NSAttributedString?

    override func loadView() -> UIView {
        let label = UILabel()
        label.numberOfLines = 0
        label.attributedText = attributedText
        label.sizeToFit()
        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)
        if let data = attributes?["data"] as? String {
            let htmlString = "<html><body>\(data)<body></html>"
            attributedText = htmlString.htmlToAttributedString
        }
    }

    func data(_ text: String) {

    }
}

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType:  NSAttributedString.DocumentType.html], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }

    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>

正如预期的那样,它没有通过Weex显示本机方面的任何文本。

1 个答案:

答案 0 :(得分:0)

您应该返回没有特定框架的视图,并在JS中添加宽度和高度样式。