SwiftUI Label text and image vertically misaligned

浪子不回头ぞ 提交于 2020-07-09 09:37:05

问题


I'm using SwiftUI's brand new Label View, running Xcode 12 beta on Big Sur.

As image I use SF Symbol and found an image named "play". But I've noticed the same problem with custom images without any bordering pixels (i.e. spacing is not caused by the image), e.g. PDF icons, so it is probably not related to the image.

In demos by Apple the Text and the image should just automatically align properly, but I do not see that.

struct ContentView: View {
    var body: some View {
        Label("Play", systemImage: "play")
    }
}

Results in this:

Any ideas why the image (icon) and the text is vertically misaligned?

If we give the Button a background color we see more precisely the misalignment:

Label("Play", systemImage: "play")
    .background(Color.red)

Results in this:


回答1:


Probably a bug, so worth submitting feedback to Apple. Meanwhile here is working solution based on custom label style.

Tested with Xcode 12b

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

struct TestLabelMisalignment: View {
    var body: some View {
        Label("Play", systemImage: "play")
           .labelStyle(CenteredLabelStyle())
    }
}



回答2:


@Sajjon You can add a custom View as a workaround and use Image with Text inside a HStack



来源:https://stackoverflow.com/questions/62556361/swiftui-label-text-and-image-vertically-misaligned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!