NSString中的填充空格

时间:2017-07-18 03:56:47

标签: objective-c string nsstring

以下问题最好是针对目标C(Swift也很好)。如何让我的字符串看起来像下图中的字符串?分母和分界部分的右括号需要排成一行。显然百分比可能是100%,0%,0%,这意味着百分比的左括号不会排列,这很好。百分比部分所需的空间量为9个点。

enter image description here

1 个答案:

答案 0 :(得分:0)

我强烈建议您使用布局引擎进行此类操作,但您可以使用以下内容模拟自己,我还没有对其进行测试......

// given a prefix, like @"5/50" and a suffix like @"(80%)", return a string where they are combined
// add leading spaces so that the prefix is right-justified to a particular pixel position
//
- (NSString *)paddedPrefix:(NSString *)prefix andSuffix:(NSString *)suffix forLabel:(UILabel *)label {
    // or get maxWidth some other way, depends on your app
    CGFloat maxWidth =  [self widthOfString:@"88888/50" presentedIn:label];
    NSMutableString *mutablePrefix = [prefix mutableCopy];
    CGFloat width = [self widthOfString:mutablePrefix presentedIn:label];
    while (width<maxWidth) {
        [mutablePrefix insertString:@" " atIndex:0];
    }

    // the number of blanks between the prefix and suffix is also up to you here:
    return [NSString stringWithFormat:@"%@     %@", mutablePrefix, suffix];
}


// answer the width of the passed string assuming an infinitely wide label (no wrapping)
//
- (CGFloat)widthOfString:(NSString *)string presentedIn:(UILabel *)label {
    NSAttributedString *as = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:label.font}];
    CGRect rect = [as boundingRectWithSize:(CGSize){CGFLOAT_MAX, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.width;
}