【问题标题】:Add a blank to the string in the TextField I typed into在我输入的 TextField 中的字符串中添加一个空白
【发布时间】:2020-05-22 17:08:36
【问题描述】:

在 SwiftUI 中,我有一个文本字段,用户可以在其中输入信用卡号:

@EnvironmentObject var userModData:UserModData    

var body: some View {

...

HStack {
    Text("Card number")
        .frame(width: 100, height: nil, alignment: .leading)
    TextField("Enter card number", text: $userModData.cnumber).keyboardType(.numberPad)
}

每次用户输入四位数字时,我都想添加一个空格,例如。 G。它应该看起来像:1234 5678 1234 5678

在可观察对象类中,我尝试写

class UserModData:ObservableObject {

    @Published var cnumber:String = " " {
        didSet{
            self.cnumber = self.NumberFormatter()
        }
    }

    func NumberFormatter() -> String {
        var newValue = self.cnumber

        if newValue.count == 4 {
            newValue = newValue + " "
        }

        return newValue
    }
}

这会导致运行时错误 EXC_BAD_ACCESS,因为在函数中连接字符串时,会一遍又一遍地调用 didSet 代码(至少我猜这是因为它导致溢出的原因?!)。

有没有人有一个优雅的解决方案来解决这个问题?老实说,我对 SwiftUI 还很陌生,我想解决方案比我预期的要容易。

提前致谢!

【问题讨论】:

    标签: swift xcode swiftui


    【解决方案1】:

    SwiftUI 无法完成您想要实现的目标,因为在添加空格后无法使用光标跳转到文本字段的末尾。 (SwiftUI 仍处于起步阶段。) 这部分请看this question

    您正在寻找的正确代码从以下代码开始,并且必须实现上述链接的答案:

    class UserModData:ObservableObject {
        @Published var cnumber: String = ""
    }
    
    struct ContentView : View {
    
        @ObservedObject var userModData = UserModData()
    
        var body: some View {
            let cnumber = Binding<String> (
                get: {
                    (self.userModData.cnumber )},
                set: { newValue in
                    if newValue.count % 4 == 0 {
                        self.userModData.cnumber = newValue + " "
                    } else {
                        self.userModData.cnumber = newValue
                    }
    
            })
    
            return HStack {
                Text("Card number")
                    .frame(width: 100, height: nil, alignment: .leading)
                TextField("Enter card number", text: cnumber).keyboardType(.numberPad)
            }
        }
    }
    

    【讨论】:

    • 非常感谢您的回答!您认为还是使用 Storyboard 会更好吗?
    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2019-11-09
    • 2022-01-25
    相关资源
    最近更新 更多