有没有办法做换行的一半?

时间:2013-08-12 09:52:42

标签: objective-c unicode nsstring ascii

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

1 个答案:

答案 0 :(得分: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;

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

[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