【问题标题】:How can I make a UITextView layout text the same as a UILabel?如何使 UITextView 布局文本与 UILabel 相同?
【发布时间】:2014-08-21 10:24:58
【问题描述】:

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

我发现如果我设置:

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

这使文本非常接近,但如果我将 UITextView 叠加在 UILabel 的顶部,我会看到文本位置随着每一行而变得更远。

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

我尝试过设置段落样式和最小/最大行高,但无法完全匹配。我不是打印机,所以我不一定了解NSLayoutManagerNSTextContainer 文档中的所有字体相关术语以及所有这些。

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

我不会切换到一些疯狂的基于 CoreText 的自定义小部件或使用一些随机的第三方库。如果必须的话,我可以足够接近。但似乎应该有一些随机属性的组合以使它们的布局相同。

【问题讨论】:

  • 我的字体是 HelveticaNeue 13,如果有帮助的话。

标签: ios objective-c uilabel uitextview


【解决方案1】:

我采用了找到at this link 的行距解决方案并将其应用于您的问题。通过调整lineSpacing 属性,我设法让它非常接近。我用 HelveticaNeue 尺寸 13 进行了测试,并设法让它排成一行,如下面的屏幕截图所示。

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];

【讨论】:

  • 看起来像解决方法,但不是解决方案。事实证明,boundingRectWithSize: for NSAttributedString 返回的大小与 UITextView 呈现的大小匹配,但与 UILabel 不匹配。如果我需要使用 UILabel,但是 boundingRectWithSize 的大小与它不对应怎么办?
  • @user2327139 我同意这更像是一种解决方法而不是解决方案。关于您的问题,我不完全确定您在问什么,但如果您有新问题,请使用“提问”链接。如果您认为此问题有帮助,请附上指向此问题的链接。
  • 如果您对 UILabel 和 UITextView 都使用属性字符串,您可以使两者的行距相同。无需破解。
【解决方案2】:

我已经能够使用等效的 可编辑 多行 UITextView 成功地“模拟”一个 不可编辑 多行 UILabel(碰巧在 UITableViewCell 子类中)以下:

_textView = UITextView.new;
_textView.font = _label.font;
_textView.textColor = _label.textColor;
_textView.textAlignment = _label.textAlignment;
_textView.backgroundColor = UIColor.clearColor;
_textView.textContainer.lineFragmentPadding = 0;
_textView.textContainerInset = UIEdgeInsetsZero;

为了让它在进行实际编辑时表现良好,请将以下内容添加到您的 UITextViewDelegate:

- (void)textViewDidChange:(UITextView *)textView
{
    ...
    [textView scrollRangeToVisible:NSMakeRange(textView.text.length, 0)];
    [textView scrollRectToVisible:[textView caretRectForPosition:textView.endOfDocument] animated:NO];
}

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    相关资源
    最近更新 更多