Home > Net >  Allow Spacer() to shrink to maintain text position
Allow Spacer() to shrink to maintain text position

Time:12-07

I have a view laid out like this:

Text
Spacer
Rectangle
Spacer

I'm trying to make the position of the Rectangle remain constant unless the Text is close enough to push it down. But currently, if the text grows a line taller, the rectangle moves down.

VStack {
    Text("Hello")
    Spacer()
    Rectangle()
        .frame(width: 50, height: 50)
    Spacer()
}

I tried making the Spacer layoutPriority lower than the Text and Rectangle to no avail.

CodePudding user response:

I'm not sure if I understand the question clearly, but it looks like what you need.

    VStack {
        Text(
            "Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World "
        )
        .frame(minHeight: 0, maxHeight: .infinity)
        
        Rectangle()
            .frame(width: 50, height: 50)
            .padding(.vertical, 100)
    }

CodePudding user response:

If your view can have a fixed height, you could set a max height for the lower Spacer() and set higher LayoutPriority() for the Text and Rectangle.

Here is an example:

 VStack {
        Text("Make this text longer and longer")
            .layoutPriority(1)
        Spacer()
        Rectangle()
            .frame(width: 50, height: 50)
            .layoutPriority(1)
        Spacer()
            .frame(maxHeight: 120)
 }
 .frame(width: 100, height: 300)

Now, if you make the text longer it will grow in height and push the rectangle down as soon as the text touches it. I hope it helps.

  • Related