Swiftui-如何计算以屏幕上的子视图为中心的HSTACK的偏移?
我有一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将偏移设置为:按钮的宽度 +每一侧的填充 *(按钮 / 2的数量 - selected buttonindindex)。
在代码中:
Simply set the offset to: the width of the button + the padding on each side * (the number of buttons / 2 - selectedButtonIndex).
In code: