【问题标题】:Show/hide DatePicker wheel manually in SwiftUI在 SwiftUI 中手动显示/隐藏 DatePicker 轮
【发布时间】:2020-01-23 18:48:02
【问题描述】:

我想在点击文本字段时关闭键盘,以便为该文本字段下方的选择器留出空间。

struct ContentView: View {
    @State private var date = Date()
    @State private var text = "write something...."

    var body: some View {
        Form {
            Section {
                TextField(text, text: $text)
            }

            Section {
                DatePicker(selection: $date, displayedComponents: .date, label: { Text("select a date")})
                .onTapGesture {
                    self.dismissKeyboard()
                }
            }
        }

    }

    func dismissKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

问题是.onTapGesture 确实关闭了键盘,但它没有显示选择轮。那么,有没有办法在关闭键盘后调用隐藏轮呢?

【问题讨论】:

    标签: datepicker show-hide swiftui


    【解决方案1】:

    使用.onAppear 而不是.onTapGesture

     DatePicker(selection: $date, displayedComponents: .date, label: { Text("select a date")})
       .onAppear {
          self.dismissKeyboard()
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2021-11-23
      • 2020-03-12
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多