Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I vertically align an image to the center of the first line of some text?

Tags:

swiftui

I have a bullet point and some long, multiline text. I want the bullet point to be aligned with the center of the first line of text. Obviously, If the string is sufficiently short and one line long then the two views are automatically center aligned. I'm interested in cases where text is more than one line long.

var body: some View {
    HStack {
        Image(systemName: "circle.fill")
            .font(.system(size: 8))
        Text("Insert really long multiline string that wraps.")
    }
}

Is this possible?

Update 1:

Setting the HStack alignment to top aligns the top of the image with the top of the text, like this...

var body: some View {
    HStack(alignment: .top) {
        Image(systemName: "circle.fill")
            .font(.system(size: 8))
        Text("This is really really really really really really really really really really really really really really really really really really really really really really really really long string.")
    }
}

image 1

Update 2:

The only option I can think of is something like this, except this is UIKit...

// Aligns the icon to the center of a capital letter in the first line
let offset = label.font.capHeight / 2.0

// Aligns the icon to the center of the whole line, which is different
// than above. Especially with big fonts this makes a visible difference.
let offset = (label.font.ascender + label.font.descender) / 2.0

let constraints: [NSLayoutConstraint] = [
  imageView.centerYAnchor.constraint(equalTo: label.firstBaselineAnchor, constant: -offset),
  imageView.trailingAnchor.constraint(equalTo: label.leadingAnchor, constant: -10)
]
NSLayoutConstraint.activate(constraints)
like image 646
DanubePM Avatar asked Dec 11 '25 09:12

DanubePM


1 Answers

On iOS 14 you can use Label for that.

enter image description here

Label {
    Text("This is really really really really really really really really really really really really really really really really really really really really really really really really long string.")
} icon: {
    Image(systemName: "circle.fill")
                .font(.system(size: 8))
}
like image 158
DanSkeel Avatar answered Dec 14 '25 10:12

DanSkeel



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!