The problem I am facing is that UILabel
will break line in the middle of the word although I am using word wrapping.
You can create a new project and replace content of view controller to see the result:
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
label.center = CGPoint(x: view.frame.midX, y: view.bounds.midY)
label.numberOfLines = 2 // Setting this to 1 produces expected result
label.lineBreakMode = .byWordWrapping
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
view.addSubview(label)
label.text = "Singlewordtext"
label.backgroundColor = .red
}
This produces 2 lines of text which is broken in the middle of the word. The reason this naturally happens is because the word itself is wider than the label itself so it makes sense (I guess). But I would hope that it would use adjustsFontSizeToFitWidth
and minimumScaleFactor
prior to breaking it. If I set it to single line (label.numberOfLines = 1
) I get expected result which is that the text will shrink instead of break. Note that doing so in this case will fit all of the text inside the label.
The question is, is there a configuration on UILabel
to prevent line break in such case? Or is there some other elegant solution?
A current result:
Desired result (produced by using label.numberOfLines = 1
):
Do note that I still do need to have 2 lines enabled to nicely display for instance label.text = "Three words fit"
.