如何在 SwiftUI 中使用属性字符串 [英] How to use Attributed String in SwiftUI

查看:36
本文介绍了如何在 SwiftUI 中使用属性字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 SwiftUI 中使用 AttributedString.没有可用的 API在文本中使用 AttributedString

How to use AttributedString in SwiftUI. There is no API available to use AttributedString in Text

推荐答案

iOS 15 和 Swift 5.5

Text 现在支持 Markdown,您也可以创建自定义属性:

iOS 15 and Swift 5.5

Text now supports markdown and also you can create custom attributes:

您甚至可以远程获取定义的属性,例如:

You can even get defined attributes remotely like:

您可以将多个 Text 对象与一个简单的 + 运算符组合在一起,这将处理一些属性:

You can combine multiple Text objects together with a simple + operator and that will handle some of the attributions:

每个都可以有多个特定的修饰符

由于它不直接支持 Text(直到 iOS 15),您可以将 UILabel 放在那里并随意修改它:

Since it doesn't support directly on Text (till iOS 15), you can bring the UILabel there and modify it in anyway you like:

struct UIKLabel: UIViewRepresentable {

    typealias TheUIView = UILabel
    fileprivate var configuration = { (view: TheUIView) in }

    func makeUIView(context: UIViewRepresentableContext<Self>) -> TheUIView { TheUIView() }
    func updateUIView(_ uiView: TheUIView, context: UIViewRepresentableContext<Self>) {
        configuration(uiView)
    }
}

用法:

var body: some View {
    UIKLabel {
        $0.attributedText = NSAttributedString(string: "HelloWorld")
    }
}

这篇关于如何在 SwiftUI 中使用属性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆