如何在SwiftUI中检测列表单元格行上的点击



给定一个基本的ListText,我如何使整个"单元格";从屏幕的左侧到右侧,可在List中点击,而不仅仅是";你好世界"文本

List {
VStack {
Text("Hello world")
}    
.contentShape(Rectangle())
.onTapGesture {
print("Tapped cell")  // This only triggers when you directly tap the Text
}
}

添加一个按钮,整个单元格现在都可以点击:

VStack {
Button(action: {
print("Tapped")
}) {
Text("Hello world")
}
}

实际上,您真正需要做的就是确保整个单元格都充满了内容。将VStack更改为HStack并添加Spacer()将满足您的需求。

List {
HStack {
Text("Hello world")
Spacer()
}
.contentShape(Rectangle())
.onTapGesture {
print("Tapped cell")  // This triggers when you tap anywhere in the cell
}
}

相关内容

最新更新