I have this code :
class ViewController: UIViewController {
private var nameLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateLable()
}
func updateLable () {
nameLabel = UILabel(frame: view.frame)
nameLabel.text = "Michael Dell Arron Henry Mitchell duve soooooooooooooooooooooooooc"
nameLabel.backgroundColor = .green
nameLabel.numberOfLines = 0
nameLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(nameLabel)
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0),
nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0)
])
nameLabel.isHidden = false
}
}
I am unable to fit the text into the label. I checked on other comments with numberOfLines = 0
and sizeToFit()
but that seems not to be working.
This is what it looks like currently:
You need to constrain the width of the label in order for it to wrap. You can either:
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0),
nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0),
nameLabel.widthAnchor.constraint(equalToConstant: 100) /// here!
])
Result:
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor , constant: 0), /// you can delete this
nameLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor , constant: 0),
/// here!
nameLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
nameLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
])
Result: