按钮内的 swiftui 文本字段和按钮
swiftui textfiled and button inside a button
我试图在用户单击视图的背景区域时触发按钮。
作为解决方案,我决定制作一个按钮并将视图作为标签放入按钮中。
但问题是按钮甚至在 TextField 上触发,有时在内部的另一个按钮上触发。
如何禁用某些视图(在本例中为 TextField 和 Button)的后退按钮 select?
我在下面附上我的代码 rendered preview。
import SwiftUI
struct ButtonOnbutton: View {
@State var memo: String = ""
var body: some View {
Button(action: {
print("down button clicked")
}) {
VStack(spacing: 10) {
Text("before")
.foregroundColor(.white)
TextField("type memo", text: $memo)
.font(.custom("SFProDisplay-Regular", size: 12))
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("after")
.foregroundColor(.white)
Button(action: {
print("inside button clicked")
}) {
Text("inside button")
.foregroundColor(.white)
}
.background(Color.red)
}
}
.background(Color.blue)
.padding()
}
}
struct buttonOnbutton_Previews: PreviewProvider {
static var previews: some View {
ButtonOnbutton()
}
}
如果我正确理解了您的目标,那么最好使用 onTapGesture
而不是按钮,如下所示
var body: some View {
VStack(spacing: 10) {
Text("before")
.foregroundColor(.white)
TextField("type memo", text: $memo)
.font(.custom("SFProDisplay-Regular", size: 12))
.textFieldStyle(RoundedBorderTextFieldStyle())
.onTapGesture {} // << just blocks outer tap
Text("after")
.foregroundColor(.white)
Button(action: {
print("inside button clicked")
}) {
Text("inside button")
.foregroundColor(.white)
}
.background(Color.red)
}
.background(Color.blue)
.onTapGesture {
print("background area clicked")
}
.padding()
}
我试图在用户单击视图的背景区域时触发按钮。 作为解决方案,我决定制作一个按钮并将视图作为标签放入按钮中。 但问题是按钮甚至在 TextField 上触发,有时在内部的另一个按钮上触发。
如何禁用某些视图(在本例中为 TextField 和 Button)的后退按钮 select?
我在下面附上我的代码 rendered preview。
import SwiftUI
struct ButtonOnbutton: View {
@State var memo: String = ""
var body: some View {
Button(action: {
print("down button clicked")
}) {
VStack(spacing: 10) {
Text("before")
.foregroundColor(.white)
TextField("type memo", text: $memo)
.font(.custom("SFProDisplay-Regular", size: 12))
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("after")
.foregroundColor(.white)
Button(action: {
print("inside button clicked")
}) {
Text("inside button")
.foregroundColor(.white)
}
.background(Color.red)
}
}
.background(Color.blue)
.padding()
}
}
struct buttonOnbutton_Previews: PreviewProvider {
static var previews: some View {
ButtonOnbutton()
}
}
如果我正确理解了您的目标,那么最好使用 onTapGesture
而不是按钮,如下所示
var body: some View {
VStack(spacing: 10) {
Text("before")
.foregroundColor(.white)
TextField("type memo", text: $memo)
.font(.custom("SFProDisplay-Regular", size: 12))
.textFieldStyle(RoundedBorderTextFieldStyle())
.onTapGesture {} // << just blocks outer tap
Text("after")
.foregroundColor(.white)
Button(action: {
print("inside button clicked")
}) {
Text("inside button")
.foregroundColor(.white)
}
.background(Color.red)
}
.background(Color.blue)
.onTapGesture {
print("background area clicked")
}
.padding()
}