如何在UITextView中增加行间距?
我希望使用默认系统字体,即大小为15的Helvetica字体。
我希望使用默认系统字体,即大小为15的Helvetica字体。
通过添加 <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.
}
更新:
我最近发现这也可以使用NSMutableParagraphStyle setLineSpacing:
API来完成。
为了始终提供有用的复制粘贴代码片段,这里是你需要的!
NSMutableParagraphStyle *myStyle = [[NSMutableParagraphStyle alloc] init];
[myStyle setLineSpacing:myLineSpacingInt];
[myString addAttribute:myDesiredAttribute value:myStyle range:myDesiredRange];
[myViewElement setAttributedText:myString];
^myViewElement
可以是 UITextField
、UILabel
或 UITextView
。
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
[textView setTypingAttributes:attrsDictionary];