如何增加UITextView中的行间距

5
如何在UITextView中增加行间距?
我希望使用默认系统字体,即大小为15的Helvetica字体。

可能重复的问题:如何控制UILabel中的行间距 - Sulthan
https://dev59.com/uG855IYBdhLWcg3wjlCL - Anoop Vaidya
https://dev59.com/kG865IYBdhLWcg3wi_M2 - Anoop Vaidya
简而言之,我不能像其他主题建议的那样做。 - nitz19arg
你肯定可以做到这一点。请接受一个答案或提交你的解决方案。 - jungledev
@nitz19arg,如果我的答案对你有所帮助,请接受下面的答案(你可以在赞/踩图标下选择勾选符号来实现)。如果我的答案不能满足你的需求,请提交你的解决方案。留下无法回答的答案是不好的礼仪。 - jungledev
2个回答

9

通过添加 <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 可以是 UITextFieldUILabelUITextView


5
在 IOS6+ 中,您可以为 UITextView 设置打字属性。
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];

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

[textView setTypingAttributes:attrsDictionary];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接