Swift字符串格式化器,用于过滤逗号。

huangapple go评论64阅读模式
英文:

Swift String Formatter that filters out commas

问题

在Swift中是否有一个`Formatter`,可以过滤逗号(或某个子字符串)?它必须使用`Formatter`协议。类似下面的东西会很好:

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


在SwiftUI中的`TextField`视图提供了一个带有`Formatter`的初始化程序,我认为我可以使用它来过滤用户输入中的逗号。
英文:

Is there a Formatter in Swift that filters out commas (or some substring)? It must use the Formatter protocol. Something like this would be great:

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

The TextField view in SwiftUI offers an initializer with a Formatter which I thought I could use to filter out commas out of user's input.

答案1

得分: 1

以下是已翻译的内容:

你可以尝试这种替代方法,

    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 }}
                    // 或者替代方式
                    // set: { txt = $0.replacingOccurrences(of: ",", with: "")}
                )).border(.red)
            }
        }
        
    }
英文:

you could try something simple like this alternative approach,

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

答案2

得分: 1

你可以创建从FormatterFormatStyleParseableFormatStyle继承的类,以在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())

当用户"提交"时,它将更新string

英文:

You can create classes that inherit from Formatter and/or FormatStyle, ParseableFormatStyle to use the format variation for SwiftUI.

Here is a rough example

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

        return !partialString.contains(&quot;,&quot;)
    }
    
}

Then in SwiftUI you can use

TextField(&quot;&quot;, value: $string, formatter: CommaFormatter())

It will update the string when the user submit

huangapple
  • 本文由 发表于 2023年4月6日 23:26:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定