如何在UITextView中增加行间距

nit*_*arg 5 xcode uitextview ios xcode4 ios6

如何在UITextView中增加行间距?

我希望使用默认系统字体,即大小为15的Helvetica.

jun*_*dev 8

声明通过添加实现协议

<NSLayoutManagerDelegate>

到你的界面.然后,设置:

yourTextView.layoutManager.delegate = self;

然后覆盖此委托方法:

- (CGFloat)layoutManager:(NSLayoutManager *)layoutManager lineSpacingAfterGlyphAtIndex:(NSUInteger)glyphIndex withProposedLineFragmentRect:(CGRect)rect
{
    return 5; // Line spacing of 19 is roughly equivalent to 5 here.
}
Run Code Online (Sandbox Code Playgroud)

更新:我最近发现这也可以使用NSMutableParagraphStyle setLineSpacing:API 完成.

为了始终提供有用的复制粘贴代码片段,我们开始吧!

NSMutableParagraphStyle *myStyle = [[NSMutableParagraphStyle alloc] init];
[myStyle setLineSpacing:myLineSpacingInt];
[myString addAttribute:myDesiredAttribute value:myStyle range:myDesiredRange];
[myViewElement setAttributedText:myString];
Run Code Online (Sandbox Code Playgroud)

^ myViewElement可以是一个UITextField,UILabelUITextView.


小智 5

在IOS6 +中,您可以设置UITextView的输入属性

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];

NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];

[textView setTypingAttributes:attrsDictionary];
Run Code Online (Sandbox Code Playgroud)