如何使UITextView布局文本与UILabel相同? [英] How can I make a UITextView layout text the same as a UILabel?

查看:168
本文介绍了如何使UITextView布局文本与UILabel相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UILabel,由于原因,我需要将其转换为UITextView.当我这样做时,尽管使用了相同的(自定义)字体,但文本的位置却不同.

I have a UILabel that I need to convert to a UITextView because reasons. When I do this, the text is not positioned the same, despite using the same (custom) font.

我发现如果我设置:

textView.textContainer.lineFragmentPadding = 0;
textView.textContainerInset = UIEdgeInsetsZero;

这使文本非常接近,但是如果将UITextView叠加在UILabel的顶部,我会发现文本位置与每一行之间的距离越来越远.

This gets the text very close, but if I superimpose the UITextView over top of the UILabel, I see the text positioning get farther apart with each new line.

UILabel为绿色,UITextView为黑色.这是使用NSParagraphStyle将最小和最大行高设置为15的.

The UILabel is green, the UITextView is black. This is using NSParagraphStyle to set min and max line height to 15.

我一直在设置段落样式和最小/最大行高,但是我无法完全匹配它.我不是打印机,所以我不一定了解NSLayoutManagerNSTextContainer文档中所有与字体有关的术语.

I've played with setting the paragraph style and min/max line height, but I haven't been able to match it exactly. I'm not a printer, so I don't necessarily understand all of the font related terms in the documentation for NSLayoutManager and NSTextContainer and all that.

我只需要支持iOS 7及更高版本.

I only need to support iOS 7 and up.

我不会切换到一些基于CoreText的疯狂自定义小部件,也不会使用一些随机的第三方库.我必须足够亲密.但是似乎应该将随机属性组合在一起,以使它们的布局相同.

I'm not going to switch to some crazy CoreText-based custom widget or use some random third party library. I'm okay with close enough if I have to. But it seems like there should be some combination of random properties to make them layout the same.

推荐答案

我采用了找到的行距解决方案

I took the solution for line spacing found at this link and applied it to your issue. I managed to get it incredibly close by adjusting the lineSpacing property. I tested with HelveticaNeue size 13 and managed to get it to line up as shown in the screen shot below.

textView.textContainer.lineFragmentPadding = 0;
textView.textContainerInset = UIEdgeInsetsZero;

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

paragraphStyle.lineSpacing = -0.38;

NSDictionary *attrsDictionary =
@{ NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:13.0f],
 NSParagraphStyleAttributeName: paragraphStyle};

textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attrsDictionary];

这篇关于如何使UITextView布局文本与UILabel相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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