【问题标题】:Formatting multi line text in UILabel?在 UILabel 中格式化多行文本?
【发布时间】:2013-09-03 12:17:50
【问题描述】:

我想要有 4 行的标签。如果文本不够长 4 行,则不会发生任何事情。但是如果文本是 4 行或更长,我希望它的最后一行颜色略有不同。

有没有简单的方法来做到这一点。我知道我可以使用属性字符串更改标签的字体,但是如何获取第四行的文本?

【问题讨论】:

  • 嘿@MegaManx 检查我的答案。,,,,

标签: ios uilabel nsattributedstring


【解决方案1】:

使用NSAttributedString 可以随意设置段落、行、单词甚至单个字符的格式。要获取第 4 行的文本,请将您的文本以 \n 字符分隔。

如果没有\n,可以使用getLineStart:end:contentsEnd:forRange:,改编自here

NSString *string = /* assume this exists */;
unsigned length = [string length];
unsigned lineStart = 0, lineEnd = 0, contentsEnd = 0;
NSMutableArray *lines = [NSMutableArray array];
NSRange currentRange;
while (lineEnd < length) {
    [string getLineStart:&lineStart end:&lineEnd
    contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
    currentRange = NSMakeRange(lineStart, contentsEnd - lineStart);
    [lines addObject:[string substringWithRange:currentRange]];
}

编辑
重新阅读问题后,这可能不是您所追求的。查看完整答案here

【讨论】:

    【解决方案2】:

    在 iOS 6+ 中,您可以使用 UILabel 的 attributedText 属性呈现属性字符串。

    以下代码示例:

     NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Hello. That is a test attributed string."];
    [str addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3,5)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(10,7)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
    label.attributedText = str;
    

    正如您在代码中看到的,您可以为不同的字符范围选择不同的颜色文本。在您的情况下,您可以将字符的不同字体颜色放在最后一行的字符串中。 为了检查您可以使用的最后一行的字符范围:

    NSUInteger characterCount = [myString length];
    

    然后 characterCount 除以每行可以放入的字符数,具体取决于它的宽度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多