ios 显示英尺和英寸的MeasurementFormatter

9njqaruj  于 2023-01-27  发布在  iOS
关注(0)|答案(3)|浏览(141)

我一直在使用MeasurementFormatter,尝试将英制长度显示为10'6"10 ft 6 in,但没有成功。当isForPersonHeightUse设置为true时,LengthFormatter可以正确地完成此操作,但它不能很好地适应用户的语言环境(例如,长度是以公制度量的国家,除了当提到高度时)。是否有任何方法可以在格式化程序中强制执行此行为?

EDITquestion用于确定如何选择度量单位。我可以选择英尺或英寸,但希望将分数英尺显示为英寸,如下所示:6英尺3英寸而不是6.25英尺。

dxpyg8gm

dxpyg8gm1#

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
iqjalb3h

iqjalb3h2#

我修改(简化)了@maslovsa的答案以满足我的需要。我有一个叫做“Patient”的Core Data对象。它有一个以英寸为单位的height参数,即Int64。我想要一个显示给用户的字符串,所以下面是我的patient对象的属性:

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英寸

jogvjijk

jogvjijk3#

如何在SwiftUI中显示英尺和英寸

以防有人来这里寻找SwiftUI的答案。

struct MeasurementTestView: View {
    @State private var height = Measurement(value: 68, unit: UnitLength.inches)
    
    var body: some View {
        VStack {
            Text(height, format: .measurement(width: .narrow, usage: .personHeight))
            Text(height, format: .measurement(width: .abbreviated, usage: .personHeight))
            Text(height, format: .measurement(width: .wide, usage: .personHeight))
        }
        .font(.title)
    }
}

结果

相关问题