Home > database >  SwiftUI - How can set a boundary for elements in ZStack
SwiftUI - How can set a boundary for elements in ZStack

Time:01-31

In my example image you can see that the "World" text can be moved (drag) outside the image area. It is positioned below the Add Sticker button. This element is in a ZStack. So I don't want my text element to go outside the image area. I tried giving a width and height to the ZStack, but didn't work.

Text higher than the image, but overflowing out of its bounds

CodePudding user response:

ZStacks don't have any sort of size limitation behavior. It just stacks views on top of each other. If you want to limit your Text to the bounds of the ZStack, put it in an overlay.

Image()
    .overlay {
        Text("Hello")
        Text("World")
        Sticker()

        /// ...
        .position(x: 0, y: 0)
        .gesture(DragGesture())
    }

CodePudding user response:

You can tell the ZStack to clip its children using the clipped(antialiased:) modifier.

ZStack {
    ...
}
.clipped()

This won't stop the user from dragging the Text outside of the ZStack's bounds, but it will stop the outside part of the Text from being drawn.

If you don't want to let the user drag the Text outside of the ZStack's bounds, you need to edit your question to include the code that implements dragging.

  •  Tags:  
  • Related