xmartlabs/Eureka

Support for MeasurementFormatter

Closed this issue · 3 comments

How to use MeasurementFormatter with DecimalRow

let speed = Measurement<UnitSpeed>(value: 111.6,
                                   unit: .kilometersPerHour)

let formatter = MeasurementFormatter()
formatter.string(from: speed)

By referring 684 did a workaround

class AreaFormatter: NumberFormatter, FormatterProtocol {
        
    override func string(for obj: Any?) -> String? {
        if let obj = obj as? NSNumber {
            let squareMeters = Measurement(value: obj.doubleValue, unit: UnitArea.squareMeters)
            let formatter = MeasurementFormatter()
            return  formatter.string(from: squareMeters)
        }
        return nil
    }
    
    override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws {
        guard obj != nil else { return }
        let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
        obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
    }
    
    func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
        if let selectedRange = textInput.selectedTextRange {
            if let newPosition = textInput.position(from: selectedRange.start, offset: -" \(UnitArea.squareMeters.symbol)".count) {
                return newPosition;
            }
        }
        return textInput.position(from: forPosition, offset:((newValue?.count ?? 0) - (oldValue?.count ?? 0))) ?? forPosition
    }
    
}
<<< DecimalRow(){
                $0.useFormatterDuringInput = true
                $0.title = "Plot Area"
                $0.value = 344.78
                let formatter = AreaFormatter()
                formatter.minimumFractionDigits = 2;
                $0.formatter = formatter
            }

Hey @devajith that looks good. Did it work? You can also post those questions to StackOverflow

Yes it is working as expected. Ok i will post it in StackOverflow.