在 UITextView 中设置行高 [英] Set line height in UITextView

查看:100
本文介绍了在 UITextView 中设置行高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经很确定它不能用任何公共 API 来完成,但我还是想问:

I'm already pretty sure that it can't be done with any public API, but I still want to ask:

有没有办法改变 UITextView 中的行高?

静态完成就足够了,无需在运行时更改它.问题是默认的行高太小了.文本看起来非常压缩,在尝试编写更长的文本时是一场噩梦.

Would be enough to do it statically, no need to change it at runtime. The problem is that the default line height is just WAY too small. Text will look extremely compressed and is a nightmare when trying to write longer texts.

谢谢,最大

我知道有 UIWebView 并且它很好并且可以做样式等.但它不可编辑.我需要一个具有可接受的行高的可编辑文本组件.Omni 框架中的那个东西也无济于事,因为它太慢而且感觉不对......

I know that there is UIWebView and that it's nice and can do styling etc. But it's not editable. I need a editable text component with acceptable line height. That thing from the Omni Frameworks doesn't help either, as it's too slow and doesn't feel right...

推荐答案

在 iOS 7 之后,styleString 方法不再有效.

After iOS 7, the styleString approach no longer works.

有两种新的替代方案可用.

Two new alternatives are available.

首先是TextKit;一个强大的新布局引擎.要更改行距,请设置 UITextView 的布局管理器的委托:

Firstly, TextKit; a powerful new layout engine. To change line spacing, set the UITextView's layout manager's delegate:

textView.layoutManager.delegate = self; // you'll need to declare you implement the NSLayoutManagerDelegate protocol

然后重写这个委托方法:

Then override this delegate method:

- (CGFloat)layoutManager:(NSLayoutManager *)layoutManager lineSpacingAfterGlyphAtIndex:(NSUInteger)glyphIndex withProposedLineFragmentRect:(CGRect)rect
{
    return 20; // For really wide spacing; pick your own value
}

<小时>

其次,iOS 7 现在支持 NSParagraphStyle 的 lineSpacing.这提供了更多的控制,例如首行缩进,以及边界矩形的计算.所以或者...


Secondly, iOS 7 now supports NSParagraphStyle's lineSpacing. This gives even more control, e.g. first line indentation, and calculation of a bounding rect. So alternatively...

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 15; // <--- indention if you need it
paragraphStyle.firstLineHeadIndent = 15;

paragraphStyle.lineSpacing = 7; // <--- magic line spacing here!

NSDictionary *attrsDictionary =
@{ NSParagraphStyleAttributeName: paragraphStyle }; // <-- there are many more attrs, e.g NSFontAttributeName

self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Hello World over many lines!" attributes:attrsDictionary];

<小时>

FWIW,旧的 contentInset 方法沿 UITextView 的左边缘对齐文本在 iOS7 下也没有用.相反,要删除边距:


FWIW, the old contentInset method to align the text along the left edge of UITextView is also no use under iOS7. Instead, to remove the margin:

textView.textContainer.lineFragmentPadding = 0;

这篇关于在 UITextView 中设置行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆