【问题标题】:Is there a way to do half of a newline?有没有办法做一半的换行符?
【发布时间】:2013-08-12 09:52:42
【问题描述】:

我想知道,有没有办法在目标 C 中的 NSString 中执行一半的换行符 (\n),即它只跳过大约一半的空间?或者以其他方式在NSString 中完成此操作?

【问题讨论】:

  • “换行的一半”是什么意思?你想达到什么目标?
  • @aleroot - 我的意思是新行通常会产生的空间的一半。我有一些要点,我想在项目符号和通向项目符号的文本之间留一点空间。常规换行符空间太大,大约一半是正确的。
  • 你看过NSParagraphStyle吗?
  • @Wain - 不,我现在会的,谢谢。

标签: objective-c unicode nsstring ascii


【解决方案1】:

就像 Wain 所说,在 NSAttributedString 上设置 NSParagraphStyle 可能是您正在寻找的。 UILabel 在 iOS 6 中支持 NSAttributedStrings,但在此之前您必须使用第三方组件。 TTTAttributedLabel 非常好并且有据可查。

NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24]; //Just a random value, you'll have to play with it till you are hhappy
[attrStr addAttribute:NSParagraphStyleAttributeName
                  value:style
                  range:NSMakeRange(0, [myString length])];
label.attributedText = attrStr;

如果您最终使用 TTTAttributedLabel,您将使用 label.text = attrStr; 或其中一种辅助方法(取自 TTTAttributedLabel 文档:

[label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
  NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolar" options:NSCaseInsensitiveSearch];
  NSRange strikeRange = [[mutableAttributedString string] rangeOfString:@"sit amet" options:NSCaseInsensitiveSearch];

  // Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
  UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:14];
  CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
  if (font) {
    [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)font range:boldRange];
    [mutableAttributedString addAttribute:kTTTStrikeOutAttributeName value:[NSNumber numberWithBool:YES] range:strikeRange];
    CFRelease(font);
  }

  return mutableAttributedString;
}];

此外,TTTAttributedLabel 有一个 lineHeightMultiple(介于 0.0 和 1.0 之间)属性,您可以调整它以获得所需的效果。这样一来,您仍然可以使用NSString,而不会与有时丑陋的NSAttributedString 混淆。

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    相关资源
    最近更新 更多