iosswiftuiswiftui-view

Moving parts of a SwiftUI List closer together


Is it possible to, somehow, move the text and the system image of a Label to be somewhat closer together?

Label("MyString", systemImage: "wifi")


Solution

  • Yes, it's possible!

    You just need to create a custom LabelStyle like this…

    struct MyLabelStyle: LabelStyle {
        
        let spacing: CGFloat
        
        func makeBody(configuration: Configuration) -> some View {
            HStack(spacing: spacing) {
                configuration.icon
                configuration.title
            }
        }
    }
    
    extension LabelStyle where Self == MyLabelStyle {
        static func mine(spacing: CGFloat) -> MyLabelStyle {
            MyLabelStyle(spacing: spacing)
        }
    }
    

    then use like:

    struct ContentView: View {
                
        var body: some View {
            VStack {
                Label("MyString", systemImage: "wifi")
                    .labelStyle(.mine(spacing: 0))
                Label("MyString", systemImage: "wifi")
                    .labelStyle(.mine(spacing: 10))
                Label("MyString", systemImage: "wifi")
                    .labelStyle(.mine(spacing: 20))
            }
        }
    }
    

    enter image description here