Home > OS >  SwiftUI change vertical alignment of Label to center image and text
SwiftUI change vertical alignment of Label to center image and text

Time:10-24

Im trying to center vertically the image and text of a SwiftUI Label. I tried to override the alignmentGuide of the Image but it didn't work. Any ideas?

        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]
                }
        }

They are top alignment in y axis

CodePudding user response:

We can do this using custom label style, like

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

and use it

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())

demo

Tested with Xcode 13 / iOS 15

  • Related