首页 > 解决方案 > 根据 SwiftUI 中的用户设置确定用户所需的温度单位 (F/C)

问题描述

有谁知道当前确定用户温度偏好设置状态的最佳方法?设置 -> 常规 -> 语言和区域 -> 温度单位下的那个?

我看过一些较旧的答案,但它们对我不起作用。我认为这种方法在过去几年中发生了变化。

标签: iosswifttemperature

解决方案


这适用于物理设备(它不适用于 iOS 模拟器):

let myFormatter = MeasurementFormatter()
let temperature = Measurement(value: 0, unit: UnitTemperature.celsius)
print(myFormatter.string(from: temperature))

如果设置 -> 常规 -> 语言和区域 -> 温度设置为华氏度,则输出 32°F 否则为 0°C。

如果您对状态感兴趣,您应该将返回的字符串解析为“°C”或“°F”


推荐阅读