如何在iPhone开发中将度数符号添加为UILabel的一部分?

时间:2019-02-21 20:28:37

标签: swift api uilabel openweathermap

我已经在我的UILabel中添加了度数符号,但是当应用程序运行时,它消失了。我正在创建一个天气应用程序,因此正确设置其格式非常重要。 这是ViewController加载后的代码。

 override func viewDidLoad() {
    super.viewDidLoad()
    cityLabel.text = city
    userEnteredNewCityName(city: city)
    // Do any additional setup after loading the view.
}

这是更新ViewController的代码

func updateWeatherData(json: JSON) {
    if let tempResult = json["main"]["temp"].double {
        weatherDataModel.temperature = Int(tempResult - 273)
        weatherDataModel.city = json["name"].stringValue
        weatherDataModel.condition = json["weather"][0]["id"].intValue
        weatherDataModel.weatherIconName = weatherDataModel.updateWeathericon(condition: weatherDataModel.condition)

        updateUIWithWeatherData()
    } else {
        cityLabel.text = "No data available"
    }

}

func userEnteredNewCityName(city: String){
    let params : [String : String] = ["q" : city, "appid" : APP_ID]
    getWeatherData(url: WEATHER_URL, parameters: params)
}

 //Write the updateUIWithWeatherData method here:


func updateUIWithWeatherData() {
    cityLabel.text = weatherDataModel.city
    temperatureLabel.text = String(weatherDataModel.temperature)
    weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}

任何帮助将不胜感激。enter image description here

2 个答案:

答案 0 :(得分:3)

理想情况下,使用MeasurementFormatter

let measurement = Measurement(value: weatherDataModel.temperature, unit: UnitTemperature.celsius)

let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitStyle = .short
measurementFormatter.numberFormatter.maximumFractionDigits = 0
measurementFormatter.unitOptions = .temperatureWithoutUnit

temperatureLabel.text = measurementFormatter.string(from: measurement)   

无需转换为Int。格式化程序将处理十进制数字的显示。

作为奖励,您不必自己进行开尔文到摄氏度的转换:

let measurementInKelvin = Measurement(value: weatherDataModel.temperature, unit: UnitTemperature.kelvin)
let measurement = measurementInKelvin.converted(to: .celsius)

答案 1 :(得分:1)

如果您要在以下代码行中更新临时标签:

temperatureLabel.text = String(weatherDataModel.temperature)

您只是将数字转换为字符串,从而覆盖之前在label中插入的所有内容。如果要添加度数符号,请执行以下操作:

temperatureLabel.text = String(weatherDataModel.temperature) + "°"

现在,如果这是最简单的方法,它也不会更可靠,因为您没有考虑用户的语言环境,为了更好地理解,我们将度量单位称为美国以华氏温度为例。
如果使用MeasurementFormatter创建字符串或选中here,这样做会更好。要获取温度单位,请检查here

    let measureFormatter = MeasurementFormatter()
    let measurement = Measurement(value: <#your_value#>, unit: UnitTemperature.celsius)
    let output = measureFormatter.string(from: measurement)