首页 > 解决方案 > SwiftUI 将 Label 的垂直对齐方式更改为居中图像和文本

问题描述

我试图将 SwiftUI 标签的图像和文本垂直居中。我试图覆盖图像的alignmentGuide,但它没有用。有任何想法吗?

        Label {
            Text("Test fdasf \n adfsa dsfsd f asdf \n asd fasd fads sad fda")
        } icon: {
            Image(systemName: true ? "checkmark.circle.fill" : "circle")
                .alignmentGuide(VerticalAlignment.top) {
                    $0[VerticalAlignment.center]
                }
        }

它们在 y 轴上对齐

标签: iosswiftui

解决方案


我们可以使用自定义标签样式来做到这一点,比如

struct DemoStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {    // << here !!
            configuration.icon
            configuration.title
        }
    }
}

并使用它

Label {
    Text("Test fdasf \n adfsa dsfsd f asdf \n asd fasd fads sad fda")
} icon: {
    Image(systemName: true ? "checkmark.circle.fill" : "circle")
}
.labelStyle(DemoStyle())

演示

使用 Xcode 13 / iOS 15 测试


推荐阅读