SwiftUI -如何计算偏移为HStack中心子视图在屏幕上?



我有一个HStack,有一个可变数量的子视图。当其中一个子视图被点击时,我想让那个子视图在屏幕上居中。我想使用.offset()简单地移动HStack正确的数量在适当的方向,使点击子视图成为屏幕上的中心。我将子视图组织在一个数组中,我正在运行ForEach(),并且我通过将selectedButtonIndex设置为选定子视图的数组索引来跟踪所选子视图。

@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()中放入什么来使所选的子视图居中?)

如果我需要澄清任何其他信息,请留下评论。提前感谢!

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

在代码:

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

最新更新