Search code examples
iosswiftiphoneuilabel

How do we put the text above? UILabel


**

i doing news app. And news content I get appears in the middle of the uilabel but I want it at the top.

**

private let articleContentLabel: UILabel = {
    let label = UILabel()
    label.numberOfLines = 0
    label.sizeToFit()
    label.lineBreakMode = .byWordWrapping
    label.backgroundColor = .cyan
    label.textColor = UIColor(red: 38/255, green: 50/255, blue: 91/255, alpha: 1)
    label.font = UIFont(name: "SFCompactDisplay-Ultralight", size: 16)
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(articleContentLabel)   
}

  override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        articleContentLabel.frame = CGRect(x: 25,
                                           y: articleImageView.bottom + 40,
                                           width: view.width - 50,
                                           height: 330)
    }

this is screenshot in myapp enter image description here


Solution

  • Much preferred way of doing UI layout, instead of setting the frame property is by using Auto Layout. You should set your label's constraints, but without explicitly specifying its height, so that it could be automatically calculated to fit the number of lines needed. Implementation should look something like this.

     articleContentLabel.translatesAutoresizingMaskIntoConstraints = false
     articleContentLabel.topAnchor.constraint(equalTo: articleImageView.bottomAnchor).isActive = true
     articleContentLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 25).isActive = true
     articleContentLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -25).isActive = true