【发布时间】:2021-05-29 16:54:39
【问题描述】:
我想在 SwiftUI 中制作一个分段标签页,如下所示。
我的代码如下:
struct ContentView: View {
@State var index = 0
@State private var offset: CGFloat = 0
var body: some View {
VStack(spacing: 0) {
HStack() {
Button("tab1") {
self.index = 0
}
Button("tab2") {
self.index = 1
}
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 0) {
VStack() {
List {
VStack {
HStack() {
Text("tab1 line1")
Spacer()
}
.frame(height: 126)
.contentShape(Rectangle())
.onTapGesture {
print("click tab1 line1")
}
}
VStack {
HStack() {
Text("tab1 line2")
Spacer()
}
.frame(height: 126)
.contentShape(Rectangle())
.onTapGesture {
print("click tab1 line2")
}
}
}
.frame(width: UIScreen.main.bounds.size.width, height: 300)
}
.frame(width: UIScreen.main.bounds.size.width, height: 300)
.cornerRadius(30)
VStack() {
List {
VStack {
HStack() {
Text("tab2 line1")
Spacer()
}
.frame(width: UIScreen.main.bounds.size.width, height: 126)
.contentShape(Rectangle())
.onTapGesture {
print("click tab2 line1")
}
}
VStack {
HStack() {
Text("tab2 line2")
Spacer()
}
.frame(width: UIScreen.main.bounds.size.width, height: 126)
.contentShape(Rectangle())
.onTapGesture {
print("click tab2 line2")
}
}
}
.frame(width: UIScreen.main.bounds.size.width, height: 300)
.onAppear() {
print("load")
}
}
.frame(width: UIScreen.main.bounds.size.width, height: 300)
.cornerRadius(30)
}
}
.content
.offset(x: self.getOffset())
.animation(.spring())
.frame(width: UIScreen.main.bounds.size.width, alignment: .leading)
}
.frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
.background(Color.gray)
}
private func getOffset() -> CGFloat {
let offset = CGFloat(self.index) * (-UIScreen.main.bounds.size.width)
return offset
}
}
一切正常,期待 tab2 中的 onTapGesture。当点击“tab1”行时,onTapGesture 可以很好地打印“click tab1 line1”或“click tab1 line2”。 点击按钮“tab2”后,页面将滚动到tab2页面。单击列表“tab2”的行时,onTapGesture 不起作用。
我试了一天,找到了两种方法让它起作用:
- 滚动到“tab2”页面后,上下滚动tab2列表,onTapGesture将工作打印“click tab2 line1”和“click tab2 line2”。
- 去掉代码
.cornerRadius(30),tab2页面的点击也可以。
我只想保持列表的半径。如何修复这个令人难以置信的错误?
【问题讨论】:
标签: swiftui scrollview