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()
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With