MeasurementFormatter显示英尺和英寸

时间:2017-02-15 14:49:05

标签: ios swift formatter measurementformatter

我一直在玩MeasurementFormatter,试图将10"6'10 ft 6 in的英制长度显示失败。当LengthFormatter设置为isForPersonHeightUse时,true会正确执行此操作,但它不能很好地适应用户的区域设置(即,以度量标准衡量长度的国家/地区除外,指的是高度) 。有没有办法在格式化程序中强制执行此行为?

修改question用于确定如何选择测量单位。我可以选择英尺或英寸,但希望以英寸为单位显示小数英尺:6'3“而不是6.25英尺。

2 个答案:

答案 0 :(得分:3)

public struct LengthFormatters {

    public static let imperialLengthFormatter: LengthFormatter = {
        let formatter = LengthFormatter()
        formatter.isForPersonHeightUse = true
        return formatter
    }()

}

extension Measurement where UnitType : UnitLength {

    var heightOnFeetsAndInches: String? {
        guard let measurement = self as? Measurement<UnitLength> else {
            return nil
        }
        let meters = measurement.converted(to: .meters).value
        LengthFormatters.imperialLengthFormatter.string(fromMeters: meters)
    }

}

使用示例:

    let a = Measurement(value: 6.34, unit: UnitLength.feet)
    print(a.heightOnFeetsAndInches ?? "")

    let b = Measurement(value: 1.5, unit: UnitLength.feet)
    print(b.heightOnFeetsAndInches ?? "")

将打印:

6 ft, 4.08 in
1 ft, 6 in

答案 1 :(得分:0)

我修改了(简化)@maslovsa的答案以满足我的需求。我有一个称为“患者”的核心数据对象。它有一个以英寸为单位的高度参数Int64。我想要显示给用户的字符串,因此这是我的耐心对象的属性,用于执行此操作:

var heightInFeetString : String {
    let measurement = Measurement(value: Double(self.height) / 12.0, unit: UnitLength.feet)
    let meters = measurement.converted(to: .meters).value
    return LengthFormatter.imperialLengthFormatter.string(fromMeters: meters)
}

当然,我也必须实现imperialLengthFormatter,但是我这样做是对LengthFormatter本身的扩展,如下所示:

extension LengthFormatter {
    public static let imperialLengthFormatter: LengthFormatter = {
        let formatter = LengthFormatter()
        formatter.isForPersonHeightUse = true
        return formatter
    }()    
}

这实际上并不会破坏@maslova答案的注释中所建议的性能。由于该属性是静态的,因此只能初始化一次。

// When creating the Patient object
let patient = Patient(...) // Create in maanged object context
patient.height = 71

// Later displays in a collection view cell in a view controller
cell.heightLabel.Text = patient.heightInFeetString

在我的表格单元格中显示:

  

5英尺,11英寸