有没有办法做一半换行?

Ser*_*nce 6 unicode ascii objective-c nsstring

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

Kev*_*vin 3

就像 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;
Run Code Online (Sandbox Code Playgroud)

如果您最终使用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;
}];
Run Code Online (Sandbox Code Playgroud)

此外,TTTAttributedLabel还有一个lineHeightMultiple(0.0 到 1.0 之间)属性,您可以通过修改该属性来获得所需的效果。这样,您仍然可以使用 anNSString并且不会弄乱有时丑陋的NSAttributedString.