我有一个 SwiftUI 应用,它以列表形式显示带有帖子的社交信息流。每篇帖子都包含需要保持交互的按钮,但我不希望整个单元格都可点击。
我尝试了不同的方法,例如在列表上使用 .disabled(true)(也会禁用按钮)、在单个元素上使用 .allowsHitTesting(false) 以及使用 .onTapGesture {} 来吸收点击,但都无法按预期工作。
谢谢
List() {
ForEach(posts, id: \.self) { post in
PostView()
.onAppear {
if post == posts.last {
loadMorePost()
}
}
.listRowInsets(EdgeInsets())
.alignmentGuide(.listRowSeparatorLeading) { vd in
return 0
}
}
}
.listStyle(.plain)
struct PostView: View {
var body: some View {
VStack(spacing: 10) {
PostHeaderView(image: Image("clovis"), userName: "Stephane", userIdentifier: "stephane_")
PostContentView()
}
.padding(20)
}
}
struct PostContentView: View {
var body: some View {
VStack(alignment: .leading, spacing: 10) {
// Post content
Text("Coiffeuse")
.font(.headline)
Text("It is a long established fact that a reader will be distracted...")
.font(.caption)
HStack(spacing: 20) {
PriceContainerView()
Spacer()
HStack(spacing: 2) {
Image(systemName: "eyes")
Text("2K")
}
// This button needs to remain interactive
Button(action: { print("Save To Later") }) {
Image(systemName: "bookmark")
.foregroundStyle(.mediumGray)
}
}
}
}
}
```