在UITextView中设置行高

我已经非常确定它不能使用任何公共API,但我仍然想问:

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

足够静态地执行它,不需要在运行时改变它。 问题是,默认行高只是太小了。 文本看起来非常压缩,在尝试写入更长的文本时是一个噩梦。

谢谢,马克斯

编辑:我知道有UIWebView ,它很好,可以做样式等,但它不是可编辑的 。 我需要一个可接受的行高的可编辑文本组件。 Omni Frameworks中的这个东西也没有帮助,因为它太慢,感觉不对

在iOS 7之后,styleString方法不再起作用。

有两个新的替代品可用。

首先,TextKit; 一个强大的新的布局引擎。 要更改行距,请设置UITextView的布局pipe理器的代理:

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

然后重写这个委托方法:

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

其次,iOS 7现在支持NSParagraphStyle的lineSpacing。 这提供了更多的控制,例如第一行缩进,以及边界矩的计算。 所以也可以…

 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, eg NSFontAttributeName self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Hello World over many lines!" attributes:attrsDictionary]; 

FWIW,沿着UITextView的左边缘alignment文本的旧contentInset方法在iOS7下也是没有用的。 相反,要删除保证金:

 textView.textContainer.lineFragmentPadding = 0; 

注意:这在iOS7中不可用:


我发现你可以创build一个重新实现[UITextView styleString]的子类:

 @interface UITextView () - (id)styleString; // make compiler happy @end @interface MBTextView : UITextView @end @implementation MBTextView - (id)styleString { return [[super styleString] stringByAppendingString:@"; line-height: 1.2em"]; } @end 

这不是私人的API使用:它只是子类。 当然,苹果可能会不同意(虽然考虑到我们都习惯于调整所有的东西来定制UIKit的外观,但我觉得这种“私人”的使用方式并不是苹果所反对的),但是实现这种方式非常简单这个问题的目标,你不妨试试。 如果应用程序被拒绝,你可以花费(可能很重要的)时间在一个更困难的解决scheme。

我们find的唯一解决scheme和我们select的解决scheme: 创build自定义字体 。 听起来很愚蠢,但似乎是唯一现实的方法。

在UITextView的属性检查器中,将属性Text改为AttributedPlain ),然后单击"more"button,在那里可以设置行高和间距。

UITextView的属性检查器

如果你在定义styleString的UITextView上定义了一个类别,则styleString的UITextView子类重写仅适用,否则会出现编译错误。 例如,在你的UITextView子类中:

 #import "SomeDangTextView.h" @interface UITextView () - (id)styleString; @end @implementation SomeDangTextView - (id)styleString { return [[super styleString] stringByAppendingString:@"; line-height: 1.5em"]; } @end 

根据苹果的文档,你可以使用一个UIWebView。

这个类不支持多种文本样式。 您指定的字体,颜色和文本alignment属性始终应用于文本视图的整个内容。 要在应用程序中显示更复杂的样式,您需要使用UIWebView对象并使用HTML呈现您的内容。

这个类不支持多种文本样式。 您指定的字体,颜色和文本alignment属性始终应用于文本视图的整个内容。 要在应用程序中显示更复杂的样式,您需要使用UIWebView对象并使用HTML呈现您的内容。

使用OHAttributedLabel Lib。 这将解决您提到的所有问题。