SwiftUI TextField with formatter not working?

前端 未结 5 1893
走了就别回头了
走了就别回头了 2020-11-29 02:00

I\'m trying to get a numeric field updated so I\'m using a TextField with the formatter: parameter set. It formats the number into the entry field just fine, but does not up

5条回答
  •  無奈伤痛
    2020-11-29 02:39

    Inspired by above accepted proxy answer, here is a ready to use struct with fair amount of code. I really hope Apple can add an option to toggle the behavior.

    struct TextFieldRow: View {
        var value: Binding
        var title: String
        var subtitle: String?
    
        var valueProxy: Binding {
            switch T.self {
            case is String.Type:
                return Binding(
                    get: { self.value.wrappedValue as! String },
                    set: { self.value.wrappedValue = $0 as! T } )
            case is String?.Type:
                return Binding(
                    get: { (self.value.wrappedValue as? String).bound },
                    set: { self.value.wrappedValue = $0 as! T })
            case is Double.Type:
                return Binding( get: { String(self.value.wrappedValue as! Double) },
                    set: {
                        let doubleFormatter = NumberFormatter()
                        doubleFormatter.numberStyle = .decimal
                        doubleFormatter.maximumFractionDigits = 3
    
                        if let doubleValue = doubleFormatter.number(from: $0)?.doubleValue {
                            self.value.wrappedValue = doubleValue as! T
                        }
                    }
                )
            default:
                fatalError("not supported")
            }
        }
        
        var body: some View {
            return HStack {
                VStack(alignment: .leading) {
                    Text(title)
                    if let subtitle = subtitle, subtitle.isEmpty == false {
                        Text(subtitle)
                            .font(.caption)
                            .foregroundColor(Color(UIColor.secondaryLabel))
                    }
                }
                Spacer()
                TextField(title, text: valueProxy)
                .multilineTextAlignment(.trailing)
            }
        }
    }
    

提交回复
热议问题