简体   繁体   中英

How can I handle the MeasurementFormatter using the kilometersPerHour UnitType?

I need to display the integer from km/h values using the MeasurementFormatter on Objective-C.

Is there any sample available?

NSMeasurementFormatter *formatter = [[NSMeasurementFormatter alloc] init];
formatter.unitStyle = MKDistanceFormatterUnitStyleAbbreviated;

Here is some example

    NSMeasurementFormatter *formatter = [[NSMeasurementFormatter alloc] init];
    formatter.unitStyle = NSFormattingUnitStyleMedium;
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];

    // format 100 km/h

    formatter.unitOptions = NSMeasurementFormatterUnitOptionsProvidedUnit;
    NSUnitSpeed *speed = [NSUnitSpeed kilometersPerHour];
    NSString *speedString = [formatter stringFromMeasurement:[[NSMeasurement alloc] initWithDoubleValue:100.0 unit:speed]];

    NSLog(@"kilometers %@", speedString);

    // format 100 mph

    formatter.unitOptions = NSMeasurementFormatterUnitOptionsProvidedUnit;
    speed = [NSUnitSpeed milesPerHour];
    speedString = [formatter stringFromMeasurement:[[NSMeasurement alloc] initWithDoubleValue:100.0 unit:speed]];

    NSLog(@"miles %@", speedString);

    // convert 100 km/h to 62.137 mph for en_US locale

    formatter.unitOptions = NSMeasurementFormatterUnitOptionsNaturalScale;
    speed = [NSUnitSpeed kilometersPerHour];
    speedString = [formatter stringFromMeasurement:[[NSMeasurement alloc] initWithDoubleValue:100.0 unit:speed]];

    NSLog(@"miles to kilometers %@", speedString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM