Swift String Formatter过滤掉逗号

2vuwiymt  于 2023-04-19  发布在  Swift
关注(0)|答案(2)|浏览(115)

Swift中是否有一个Formatter可以过滤掉逗号(或一些子字符串)?它必须使用Formatter协议。像这样的东西会很棒:

static let myCommaFilter : Formatter = {
  // TextFormatter?
  StringFormatter(filter: { input in // (String)->String
    input.replacingOccurrences(of: ",", with: "")
  })
}()

SwiftUI中的TextField视图提供了一个带有Formatter的初始化器,我认为可以用它来过滤掉用户输入中的逗号。

mm5n2pyu

mm5n2pyu1#

你可以尝试一些简单的方法,比如这个替代方法,

struct ContentView: View {
    @State var txt = "something"
    
    var body: some View {
        VStack {
            Text(txt)
            TextField("", text: Binding(
                get: { txt },
                set: { if !$0.contains(",") { txt = $0 }}
                // or alternatively
                // set: { txt = $0.replacingOccurrences(of: ",", with: "")}
            )).border(.red)
        }
    }
    
}
inb24sb2

inb24sb22#

您可以创建从Formatter和/或FormatStyleParseableFormatStyle继承的类,以使用SwiftUI的format变体。
这里有一个粗略的例子

class CommaFormatter: Formatter {
    override func string(for obj: Any?) -> String? {
        guard let obj = obj as? String else{
            return nil
        }
        return obj.replacingOccurrences(of: ",", with: "")
    }
    override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        obj?.pointee = string.replacingOccurrences(of: ",", with: "") as AnyObject
        return true
    }
    
    override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        newString?.pointee = partialString.replacingOccurrences(of: ",", with: "") as NSString

        return !partialString.contains(",")
    }
    
}

在SwiftUI中,你可以使用

TextField("", value: $string, formatter: CommaFormatter())

当用户submit

相关问题