Abhishek
Abhishek

Reputation: 184

How to align image with text in SwiftUI

The code below is from a simple SwiftUI ContentView. It displays an image and text, but the image stretches taking the starting position.

struct CustomView: View {
var imageName: String = ""
var text: String = ""
var body: some View {
    HStack(alignment: .center, spacing: 05){
        Image(imageName).resizable()
            .frame(width: 50, height: 30)
        Text(text).font(.system(size: 10, weight: .light, design: .default))
            .foregroundColor(.white)
            .frame(width:60)
    }
}

}

enter image description here

Upvotes: 0

Views: 2739

Answers (1)

I don't exactly understand the "...image stretches taking the starting position". However, here is a basic test with your code adding ".fixedSize()". What exactly do you think is not correct with the results?

struct CustomView: View {
    @State var imageName: String = ""  // <---
    @State var text: String = ""      // <---
    var body: some View {
        HStack(alignment: .center, spacing: 05){
            Image(systemName: imageName).resizable()
                .scaledToFit() // <--- 
                .frame(width: 50, height: 30)
            Text(text).font(.system(size: 10, weight: .light, design: .default))
                .frame(width:60)
        }.fixedSize()       // <----
        .border(Color.red)  // for testing
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            CustomView(imageName:"clock", text:"clock")
            CustomView(imageName:"info", text:"info")
            CustomView(imageName:"globe", text:"globe")
        }.padding()
    }
}

Upvotes: 3

Related Questions