UILabel和UITextView换行符不匹配 [英] UILabel and UITextView line breaks don't match
问题描述
我有一个UILabel和一个UITextView,我的目的是使它们既显示相同的文本,又使外观相同.我现在对此有一些疑问.我已经在Swift游乐场建立了一个演示:
I have a UILabel and a UITextView, where my intention is for them both to display the same text, and for the appearance to be the same. I'm having some issue with that right now. I've set up a demonstration in a Swift Playground:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 100, y: 100, width: 247, height: 39)
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 16)
label.text = "I’m on my way back to London today"
label.textColor = .black
label.backgroundColor = .red
label.lineBreakMode = .byWordWrapping
view.addSubview(label)
let textView = UITextView()
textView.frame = CGRect(x: 100, y: 200, width: 247, height: 39)
textView.font = label.font
textView.text = label.text
textView.textColor = label.textColor
textView.backgroundColor = label.backgroundColor
textView.textContainer.lineBreakMode = label.lineBreakMode
textView.textContainerInset = UIEdgeInsets.zero
textView.textContainer.lineFragmentPadding = 0
view.addSubview(textView)
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
如您所见,它们的设置方式相同,但是换行符发生在UITextView的不同位置.我已经将lineBreakMode
设置为两个相同的值.我还删除了UITextView上的textContainerInsets
和lineFragmentPadding
,因此在两个视图中使用相同的填充来放置文本.
As you can see, they're both setup in the same way, but the linebreak occurs in a different place on the UITextView. I've set the lineBreakMode
to the same value for both. I've also removed the textContainerInsets
and lineFragmentPadding
on the UITextView, so the text is positioned with the same padding within both views.
推荐答案
这是IOS 11中对UILabel
的更改,用于修复孤立的单词.尽管希望存在,但无法关闭它.唯一的方法是使用不可编辑/不可滚动的文本视图或CATextLayer
.要获取UILabel
的大小设置属性,恐怕您必须手动执行此操作.
It was a change to UILabel
in IOS 11 to fix orphaned words. No way to shut it off although I wish there was. The only way to do it would be to use a non editable/nonscrollable textview or a CATextLayer
. To get the sizing attributes of a UILabel
I am afraid you have to do that manually.
请参阅此问题是相似的.尽管没有找到答案,但我确实发现UITextView
包装了旧方法.我现在正在使用UITextView
,并且在textDidChange
中手动调整字体大小.我拥有原始字体,因此可以随时调整大小.
See this as the problem was similar. Although not in that answer I did find that UITextView
wraps the old way. I am using a UITextView
now and I manually adjust the font size in textDidChange
. I hold the original font so I can always resize.
这篇关于UILabel和UITextView换行符不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!