SwiftUI:隐藏测量单位

qyzbxkaa  于 2023-04-10  发布在  Swift
关注(0)|答案(1)|浏览(103)

在SwiftUI中显示测量时,是否有隐藏单位的选项?
(备选案文:以不同的字体大小显示单位。)

struct MeasurementStyle: View {
var body: some View {
    let speed = Measurement(value: 50, unit: UnitSpeed.kilometersPerHour)
    let style = Measurement<UnitSpeed>.FormatStyle(
        width: .abbreviated,
        numberFormatStyle: .number
    )
    Text("\(speed, format: style)")
}

//显示:“31 mph”
//需要:“31”

k2arahey

k2arahey1#

这可能是最糟糕的方法,但似乎有效:

import SwiftUI

struct MeasurementUnit<T: Unit>: View {
    let unit: String
    
    init(measurement: Measurement<T>) {
        let measurementFormatter = MeasurementFormatter()
        measurementFormatter.locale = Locale.current
        self.unit = String(measurementFormatter.string(from: measurement).split(separator: " ")[1])
    }
    
    var body: some View {
        Text(unit)
    }
}

struct MeasurementValue<T: Unit>: View {
    var value: String
    
    init(measurement: Measurement<T>, format: String) {
        let measurementFormatter = MeasurementFormatter()
        measurementFormatter.locale = Locale.current
        self.value = String(format: format, Double(measurementFormatter.string(from: measurement).split(separator: " ")[0])!)
    }
    
    var body: some View {
        Text(value)
    }
}

struct MeasurementView_Previews: PreviewProvider {
    static var previews: some View {
        HStack {
            MeasurementValue<UnitSpeed>(measurement: Measurement<UnitSpeed>(value: 12, unit: UnitSpeed.kilometersPerHour), format: "%.1f").font(.system(size: 100))
            MeasurementUnit<UnitSpeed>(measurement: Measurement<UnitSpeed>(value: 12, unit: UnitSpeed.kilometersPerHour))
        }
    }
}

相关问题