首页 > 解决方案 > SwiftUI (dismiss-keyboard) 覆盖禁用底层操作

问题描述

这个问题与使用 SwiftUI 时如何隐藏键盘有关?

示例代码:

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在叠加层上添加某些其他操作不再起作用。这是故意的吗?它是一个错误吗?有没有办法解决这个问题?

标签: iosswiftswiftuikeyboarduiresponder

解决方案


将此修饰符添加到按钮

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()
}

}

我希望它能正常工作


推荐阅读