Swiftui-如何计算以屏幕上的子视图为中心的HSTACK的偏移?

发布于 2025-02-12 13:34:49 字数 966 浏览 1 评论 0原文

我有一个HSTACK,具有可变的子视图数量。当一个子视图被轻拍时,我想将该子视图集中在屏幕上。我想使用.offset()简单地将HSTACK移动到正确的方向上,以使敲击的子视图居于屏幕上。我在一个阵列中组织了一个子视图,我正在运行一个foreach() on,并且我通过设置selected buttonindex跟踪所选子视图点击子视图的数组。

@State var buttons: [String] = ["Button"]
@State var selectedButtonIndex: Int = 0
HStack {
  ForEach(0..<buttons.count) { index in
  Rectangle()
    .frame(width: 100, height: 50)
    .onTapGesture {
      selectedButtonIndex = index
    }
    .scaleEffect(selectedIndex == index ? 1.15 : 1) // the selected subview appears slightly bigger than the others
}
.offset(getOffset()) // I need to calculate this such that the selected subview is centered on the screen

而且我有一些按钮在HSTACK中添加了一个额外的矩形,例如:

Button("tap") {
    buttons.append("another button")
}

我如何计算Hstack上所需的偏移以中心选定子视图?(我可以放入功能> getOffset()使所选子视图的中心?)

如果我需要澄清任何其他信息,请发表评论。先感谢您!

I have an HStack that has a variable number of subviews. When one of the subviews is tapped, I would like to center that subview on the screen. I want to use .offset() to simply move the HStack the correct amount in the proper direction such that the tapped subview becomes centered on the screen. I have the subviews organized in an array that I'm running a ForEach() on, and I'm keeping track of the selected subview by setting selectedButtonIndex to the index of the array of the tapped subview.

@State var buttons: [String] = ["Button"]
@State var selectedButtonIndex: Int = 0
HStack {
  ForEach(0..<buttons.count) { index in
  Rectangle()
    .frame(width: 100, height: 50)
    .onTapGesture {
      selectedButtonIndex = index
    }
    .scaleEffect(selectedIndex == index ? 1.15 : 1) // the selected subview appears slightly bigger than the others
}
.offset(getOffset()) // I need to calculate this such that the selected subview is centered on the screen

and I have some button that adds an additional rectangle to the HStack such as:

Button("tap") {
    buttons.append("another button")
}

How can I calculate the offset needed on the HStack to center the selected subview? (what can I put in the function getOffset() such that the selected subview gets centered?)

If I need to clarify any additional information, please leave a comment. Thank you in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

跨年 2025-02-19 13:34:49

只需将偏移设置为:按钮的宽度 +每一侧的填充 *(按钮 / 2的数量 - selected buttonindindex)。

在代码中:

110 * CGFloat(buttons.count / 2 - selectedButtonIndex)

Simply set the offset to: the width of the button + the padding on each side * (the number of buttons / 2 - selectedButtonIndex).

In code:

110 * CGFloat(buttons.count / 2 - selectedButtonIndex)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文