如何在 iOS 15 中使用 AttributedString 描边文本?

Zel*_*lko 4 uikit nsattributedstring ios swiftui

iOS 15 包含对AttributedString的支持

例子

struct PlaygroundView: View {
    func attributedString(string: String) -> AttributedString {
        var text = AttributedString(string)
        text.font = .largeTitle.bold()
        text.foregroundColor = .blue
        return text
    }
    
    var body: some View {
        Text(attributedString(string: "Hello"))
    }
}
Run Code Online (Sandbox Code Playgroud)

归属文本

文档提到属性范围

AttributedString API 定义了常见用途的键,例如文本样式、语义标记可格式化类型(例如日期和数字)以及超链接。您可以在 AttributeScopes 枚举中找到这些属性,其中包含 Foundation、SwiftUI、UIKit 和 AppKit 的属性。

这是描边颜色属性的描边颜色,但它似乎什么也没做。

struct PlaygroundView: View {
    func attributedString(string: String) -> AttributedString {
        var text = AttributedString(string)
        text.font = .largeTitle.bold()
        text.foregroundColor = .blue
        text.strokeWidth = 5
        text.strokeColor = .red
        return text
    }
    
    var body: some View {
        Text(attributedString(string: "Hello"))
    }
}
Run Code Online (Sandbox Code Playgroud)

归属文本

附加文档:

小智 12

strokeWidthAttributedString 中的 不适用于 SwiftUI。

\n

我在 WWDC 2021 之后在 Twitter 上提出了类似的问题,并得到了 Apple 基础工程师的回复。这是回复:

\n
\n

.StrokeWidth 是 AppKit/UIKit 定义的属性,因此不能保证它能自动与 SwiftUI 一起使用。您可以在https://developer.apple.com/documentation/foundation/attributescopes/swiftuiattributes找到 SwiftUI 支持的所有属性

\n
\n

如果您想在 SwiftUI 中使用描边文本,则需要使用 UIViewRepresentable 视图作为解决方法。创建一个 UILabel 并将带有 strokeWidth 的 NSAttributedString 设置为 UILabel 的 attributeText 属性。

\n