ios - SwiftUI (dismiss-keyboard) 覆盖禁用底层操作
问题描述
示例代码:
struct ContentView: View {
@State var text = ""
var body: some View {
Background {
NavigationView {
List {
TextField("TextInput", text: $text)
Text("OnTapGesture")
.onTapGesture {
print("Text Tapped") //works
}
Button("Tap me") {
print("Btn Tapped") //doesn't work
}
NavigationLink("Go to detail", destination: Text("DetailView")) //doesn't work
}
}
}
}
}
struct Background<Content: View>: View {
private var content: Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content()
}
var body: some View {
Rectangle()
.overlay(content)
.onTapGesture {
self.endEditing()
}
}
func endEditing() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
这里的覆盖按预期工作,我可以点击任何地方来关闭键盘。但是,通过onTapGesture
在叠加层上添加某些其他操作不再起作用。这是故意的吗?它是一个错误吗?有没有办法解决这个问题?
解决方案
将此修饰符添加到按钮
Button(action: {}) {
Text("Button Tap")
}
.buttonStyle(PlainButtonStyle())
完整代码
struct ContentView: View {
@State var text = ""
@State private var tap: Bool = false
var body: some View {
Background {
NavigationView {
List {
TextField("TextInput", text: $text)
Text("OnTapGesture")
.onTapGesture {
print("Text Tapped") //works
}
Button(action: buttonTapped) {
Text("Button Tapped")
}
.buttonStyle(PlainButtonStyle())
NavigationLink(destination: Text("DetialView"), isActive: $tap) {
Button(action: tapButton) {
Text("Go to Navigation")
}
.buttonStyle(PlainButtonStyle())
}
}
}
}
}
func buttonTapped() {
print("Button Tapped...")
}
func tapButton() {
tap.toggle()
}
}
我希望它能正常工作
推荐阅读
- python - 每次使用不同的切片范围沿不同的暗淡对数组求和
- python-3.x - 如何使用python从mongodb检索图像
- javascript - Bulma Navbar burger 仅适用于 index.html 页面
- python - 如何从 pyomo 的课程解决方案中访问我的结果?
- json - 与命令行 cURL 相比,IntelliJ IDEA 休息客户端 JSON 响应未正确解析
- swift - 所有 ViewController 视图在单元测试中都是 Nil 吗?
- php - 在 phpmyadmin 中,我如何将单个数据库中两个不同表中的两个特定行相互链接并保持自动化?
- go - golang中高效的日志解析
- python - 用元组替换列表中的文本
- amazon-web-services - Amazon S3 清单文件是否支持 Parquet 格式?