Search code examples
iosswiftswiftuizstack

SwiftUI - How can set a boundary for elements in ZStack


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

Solution

  • 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.