How to create SwiftUI TextField that accepts only numbers and a single dot?

前端 未结 2 1549
無奈伤痛
無奈伤痛 2021-01-06 04:02

How to create a swiftui textfield that allows the user to only input numbers and a single dot? In other words, it checks digit by digit as the user inputs, if the input is a

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 05:02

    This is a simple solution for TextField validation: (updated)

    struct ContentView: View {
    @State private var text = ""
    
    func validate() -> Binding {
        let acceptableNumbers: String = "0987654321."
        return Binding(
            get: {
                return self.text
        }) {
            if CharacterSet(charactersIn: acceptableNumbers).isSuperset(of: CharacterSet(charactersIn: $0)) {
                print("Valid String")
                self.text = $0
            } else {
                print("Invalid String")
                self.text = $0
                self.text = ""
            }
        }
    }
    
    var body: some View {
        VStack {
            Spacer()
            TextField("Text", text: validate())
                .padding(24)
            Spacer()
        }
      }
    }
    

提交回复
热议问题