gpt4 book ai didi

ios - NSLengthFormatter 得到 stringFromMeters : in miles/kilometers only

转载 作者:可可西里 更新时间:2023-11-01 04:18:05 26 4
gpt4 key购买 nike

我正在使用 NSLengthFormatter类来格式化用户和某个目的地之间的距离。

CLLocation *userLocation; //<- Coordinates fetched from CLLocationManager
CLLocation *targetLocation; //<- Some location retrieved from server data

CLLocationDistance distance = [userLocation distanceFromLocation:targetLocation];

NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
NSString *formattedLength = [lengthFormatter stringFromMeters:distance];

现在,如果长度小于 1000 米,格式化的距离总是以码或米显示(取决于区域设置)。

例如。如果距离 = 450.0,格式化字符串将为 492.7 yd 或 450 m。

如何调整 NSLengthFormatter 以仅返回以英里/公里为单位的距离字符串?

最佳答案

这是我最终使用的:

-(NSString *)formattedDistanceForMeters:(CLLocationDistance)distance
{
NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
[lengthFormatter.numberFormatter setMaximumFractionDigits:1];

if ([[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue])
{
return [lengthFormatter stringFromValue:distance / 1000 unit:NSLengthFormatterUnitKilometer];
}
else
{
return [lengthFormatter stringFromValue:distance / 1609.34 unit:NSLengthFormatterUnitMile];
}
}

编辑:

同样的在 Swift 中看起来像:

func formattedDistanceForMeters(distance:CLLocationDistance) -> String {
let lengthFormatter:NSLengthFormatter! = NSLengthFormatter()
lengthFormatter.numberFormatter.maximumFractionDigits = 1

if NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem).boolValue()
{
return lengthFormatter.stringFromValue(distance / 1000, unit:NSLengthFormatterUnitKilometer)
}
else
{
return lengthFormatter.stringFromValue(distance / 1609.34, unit:NSLengthFormatterUnitMile)
}
}

关于ios - NSLengthFormatter 得到 stringFromMeters : in miles/kilometers only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30951553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com