简体   繁体   English

SwiftUI - 如何为 ZStack 中的元素设置边界

[英]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.这个元素在 ZStack 中。 So I don't want my text element to go outside the image area.所以我不希望我的文本元素位于图像区域之外的 go。 I tried giving a width and height to the ZStack, but didn't work.我试着给 ZStack 一个宽度和高度,但没有用。

文本高于图像,但超出其范围

ZStack s don't have any sort of size limitation behavior. ZStack没有任何大小限制行为。 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 .如果您想将您的Text限制在ZStack的范围内,请将其放在一个overlay中。

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

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

You can tell the ZStack to clip its children using the clipped(antialiased:) modifier .您可以使用clipped(antialiased:)修饰符告诉ZStack剪辑其子项。

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.这不会阻止用户将Text拖到ZStack的边界之外,但会阻止Text的外部部分被绘制。

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.如果您不想让用户将Text拖到ZStack的范围之外,您需要编辑您的问题以包含实现拖动的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM