MrX
MrX

Reputation: 991

Swift: UILabel MultiLine

I'm got a little problem with my UILabel. Below the picture : enter image description here

This is my snippet code :

let label = UILabel(frame: CGRect(x: 0, y: (0), width: 350, height: 80))
    label.center = CGPoint(x: (view.frame.size.width / 2), y: (view.frame.size.height / 2) )
    label.font = UIFont(name: "Futura", size: 35)
    label.textAlignment = .center
    label.numberOfLines = 0
    label.text = "Total\n\(dataOverview["totClean"])"

I want to make the label become :

Total 95

I have been add label.numberOfLines and Total\n... but still not work. Do i do a mistake? Thanks in Advance

Solved with great answer and suggest below. Here my label now :

enter image description here

Upvotes: 0

Views: 1735

Answers (2)

Grzegorz Krukowski
Grzegorz Krukowski

Reputation: 19872

You need to increase frame size to 120 as 80 is not enough for your font size:

let label = UILabel(frame: CGRect(x: 0 y: 0, width: 350, height: 120))

Alternatively a better solution in my opinion will be to do this:

let label = UILabel(frame: CGRect(x: 50, y: (50), width: 350, height: 80))
    label.center = CGPoint(x: (view.frame.size.width / 2), y: (view.frame.size.height / 2) )
label.font = UIFont(name: "Futura", size: 35)
label.textAlignment = .center
label.numberOfLines = 0
label.text = "Total\n95)"
//make a font scaling to fit text inside label
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5

With that approach you can size your label to fill inside of a circle and make sure it will not overlap it.

Assuming you will do translations to your application or just number becomes big enough, the UILabel will continue to grow. Just changing the size of UILabel forever is never a good solution, neither is label.sizeToFit() as it result in problems like here:

enter image description here

Comparing to sizing the textfield well to fit center of circle:

Upvotes: 1

mmr118
mmr118

Reputation: 505

add label.sizeToFit() to the end of this

Upvotes: 1

Related Questions