-2

我需要分别识别字符串“legCentimetres”中的两个值

一个示例值为:-

'15-18'

应用英寸计算,然后放回原处。我所做的似乎只计算了第一位,目前它的结果是:-

15 厘米 / 5.9 英寸

但应该看起来像: -

15-18cm / 5.9-7.1in

我应该在下面的代码中进行哪些更改才能使其正常工作?

- (NSString *)textForIndexPath:(NSIndexPath *)indexPath isTitle:(BOOL)isTitle {
    NSString *result = @"";
    double legCentimetres = [self.animal.legSpan doubleValue];
    double legInches = lcm / 2.54;
    switch (indexPath.row) {
        case 0:
            result = (isTitle)? @"Habitat" : self.animal.habitat;
            break;
        case 1:
            result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%dcm / %.1fin", (int)legCentimetres, legInches];
            break;
        default:
            break;
    }
    return result;
}
4

2 回答 2

1
- (NSString *)textForIndexPath:(NSIndexPath *)indexPath isTitle:(BOOL)isTitle {
    NSString *result = @"";
    double legCentimetresMin = [[[self.animal.legSpan componentsSeparatedByString:@"-"] objectAtIndex:0] doubleValue];
    double legCentimetresMax = [[[self.animal.legSpan componentsSeparatedByString:@"-"] objectAtIndex:1] doubleValue];
    double legInchesMin = legCentimetresMin / 2.54;
    double legInchesMax = legCentimetresMax / 2.54;
    switch (indexPath.row) {
        case 0:
            result = (isTitle)? @"Habitat" : self.animal.habitat;
            break;
        case 1:
            result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%d-%dcm / %.1f-%.1fin", (int)legCentimetresMin, (int)legCentimetresMax, legInchesMin, legInchesMax];
            break;
        default:
            break;
    }
    return result;
}
于 2013-06-06T23:49:06.570 回答
0

这似乎是一个好方法,尽管您可能会稍微缩小它。我将腿长分成两个数字(以厘米为单位的范围),然后枚举这些厘米,将每个数字转换为英寸。从那里,我将它们添加到一个数组中,稍后我可以将它们转换为 NSString。

- (NSString *)textForIndexPath:(NSIndexPath *)indexPath isTitle:(BOOL)isTitle {
    NSString *result = @"";
    switch (indexPath.row) {
        case 0:
            result = (isTitle)? @"Habitat" : self.animal.habitat;
            break;
        case 1 {
            NSString *legSpan = self.animal.legSpan;
            NSArray *centimetres = [legSpan componentsSeparatedByString:@"-"];
            NSMutableArray *inches = [NSMutableArray array];
            NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
            [fmt setMaximumFractionDigits:1];
            [centimetres enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                [inches addObject:[fmt stringFromNumber:@([obj doubleValue] / 2.54)]];
            }];
            NSString *inchString = [[inches componentsJoinedByString:@"-"] stringByAppendingString:@"in"];
            NSString *cmString = [legSpan stringByAppendingString:@"cm"];

            result = (isTitle)? @"Leg Span" : [NSString stringWithFormat:@"%dcm / %.1fin", cmString, inchString];
            break;
        }
        default:
            break;
    }
    return result;
}
于 2013-06-06T23:26:38.927 回答