SwiftU 将文字置于图标的前面

7 min read

在 SwiftUI 中,Label 视图默认将图标置于文字的前面。如果你想将文字置于图标的前面,需要自定义 LabelStyle 来改变元素的布局。

以下是一个如何创建这样的自定义 LabelStyle 的示例:

struct IconAfterTextLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack {
            configuration.title
            configuration.icon
        }
    }
}

这里,IconAfterTextLabelStyle 是一个实现了 LabelStyle 协议的自定义结构体。在 makeBody(configuration:) 方法中,我们创建了一个水平堆栈 HStack,并将标题(configuration.title)放在了图标(configuration.icon)的前面。

然后,你可以在 Label 视图中使用这个自定义样式,像这样:

Label("Both", systemImage: "paperplane")
    .font(.title)
    .labelStyle(IconAfterTextLabelStyle())
    .background(Color.gray.opacity(0.2))
    .clipShape(Capsule())
    .padding(20)

在这个代码中,Label 视图将使用 IconAfterTextLabelStyle,将图标置于文字的后面。