【问题标题】:Padding Spaces in a NSString在 NSString 中填充空格
【发布时间】:2017-07-18 03:56:47
【问题描述】:

以下问题最好是针对 Objective C 的(Swift 也可以)。我怎样才能让我的字符串看起来像下图中的字符串?百分比部分的分母和右括号需要对齐。显然,百分比可能是 100%、0%、0%,这意味着百分比的左括号不会对齐,这很好。百分比部分所需的空间量为 9 个点。

【问题讨论】:

  • 字符串对使用 UILabel 的用户可见。您可以通过在代码或 IB 中安排 6 个标签来实现此目的
  • 当然可以,但是我怎样才能用每行一个字符串呢?
  • 如果将 UILabel 设置为右对齐会怎样?
  • 假设第一个值是 50/50 和 (100%),那么其余的就不会排队了。
  • 每行只使用两个标签。

标签: objective-c string nsstring


【解决方案1】:

我强烈建议将布局引擎用于此类事情,但您可以使用以下内容模拟自己,但我尚未测试...

// 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;
}

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2015-06-04
    • 2015-02-09
    • 1970-01-01
    相关资源
    最近更新 更多