【问题标题】:Ignore left whitespaces on imput in TextField SwiftUI Combine忽略 TextField SwiftUI Combine 中输入的左侧空格
【发布时间】:2020-05-07 09:01:54
【问题描述】:

我正在传递给 TextField 发布的变量

TextField("First name", text: $state.firstName)

我想控制插补:忽略空格,如果它是从左边输入的

我可以在哪里以及如何做?

【问题讨论】:

    标签: swift swiftui textfield combine


    【解决方案1】:

    可以使用代理绑定,如下所示

    TextField("First name", text: Binding(
        get: { self.state.firstName },
        set: {
            var newValue = $0
            // fix newValue here as needed
            self.state.firstName = newValue
    }))
    

    【讨论】:

      【解决方案2】:

      在您的ViewModel 中添加一个检查器,该检查器将自动检查每个击键并修复第一个索引处的空白。

      import Foundation
      import Combine
      
      class ViewModel: ObservableObject {
          @Published var value: String = ""
          var previousAmount = 0.0
          var validStringChecker: AnyCancellable? = nil
      
          init() {
              validStringChecker = $value.sink { val in
                  if val.first == " " {
                      var newValue = val
                      newValue.remove(at: newValue.firstIndex(of: " ")!)
      
                      DispatchQueue.main.async {
                          self.value = newValue
                      }
                  }
              }
          }
      }
      

      在您的ContentView 中使用您的TextField,例如:

      import SwiftUI
      import Foundation
      import Combine
      
      
      struct ContentView: View {
          @ObservedObject var viewModel = ViewModel()
      
          var body: some View {
              VStack {
                  TextField("First Name", text: $viewModel.value)
                      .textFieldStyle(RoundedBorderTextFieldStyle()).padding()
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 1970-01-01
        • 2020-02-12
        相关资源
        最近更新 更多