开发者

Allow Spacer() to shrink to maintain text position

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.


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)
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜