2014-01-26 74 views
12

我正在制作一个格式化屏幕截图的应用程序,我正在使用NSAttributedString格式化输入到UITextView中的文本,但有些行太靠近了。如何在NSAttributedString中添加行间距

我想知道是否有人可以提供代码示例或提示如何更改这些行之间的边距,以便它们之间有更多空间。

下面是另一个桌面屏幕编写程序的图像,它演示了我的意思,请注意每个位表示“DOROTHY”之前是否有一点空间。

enter image description here

回答

41

以下示例代码使用段落样式到文本的段落之间调整间距。

UIFont *font = [UIFont fontWithName:fontName size:fontSize]; 
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 
paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight; 
NSDictionary *attributes = @{NSFontAttributeName:font, 
          NSForegroundColorAttributeName:[UIColor whiteColor], 
          NSBackgroundColorAttributeName:[UIColor clearColor], 
          NSParagraphStyleAttributeName:paragraphStyle, 
          }; 
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes]; 

要有选择地调整某些段落的间距,只将段落样式应用于这些段落。

希望这会有所帮助。

11

大答案@Joe史密斯

如果有人想看到这个样子斯威夫特2 *:

let font = UIFont(name: String, size: CGFloat) 
    let paragraphStyle = NSMutableParagraphStyle() 
    paragraphStyle.paragraphSpacing = 0.25 * font.lineHeight 
    let attributes = [NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle] 

    let attributedText = NSAttributedString(string: String, attributes: attributes) 
    self.textView.attributedText = attributedText 
+0

纳撒尼尔,这几乎是完美的 - 除了段落样式必须初始化为NSMutableParagraphStyle()。 NSParagraphStyle是不可变的,所以它的间距属性是只读的,不能修改 – Natalia

+0

好点,@NataliaChodelski!我已经修复了它在我的代码中,但没有在我的帖子中。我做了改变。 :) – Nathaniel

相关问题