Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning texts and images in SwiftUI

Tags:

swift

swiftui

The code below is from a simple SwiftUI ContentView. It displays a piece of text and an image that I wish to have vertically aligned along their centre line.

var body: some View {
    HStack(alignment: .center) {
        Text("Cloudy")
            .background(Color.yellow)
        Image(systemName: "cloud.heavyrain")
            .background(Color.blue)
    }
    .font(.largeTitle)
    .border(Color.red)
}

Instead, I find that they appear to be centred on their frames. For the text the frame is too big and for the image it is too small.

Cloudy text and image

Is it possible to align the contents (particularly the image - which seems to know no bounds) rather than the frames?

like image 580
Vince O'Sullivan Avatar asked Oct 16 '25 02:10

Vince O'Sullivan


1 Answers

Images can have baselines, and although many times they are equal to zero, there are some other cases (like "Cloudy"), when they're not. If you set the baseline to zero, then it will center with the text:

struct ContentView: View {

    var body: some View {
        HStack(alignment: .center) {
            Text("Cloudy").background(Color.yellow)
            Image(uiImage: UIImage(systemName: "cloud.heavyrain")!.withBaselineOffset(fromBottom: 0))
                .background(Color.blue)
        }
        .font(.largeTitle)
        .border(Color.red)
    }
}
like image 112
kontiki Avatar answered Oct 18 '25 17:10

kontiki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!