Search code examples
iosxcodeconstraintsuilabel

How to make the text on UILabel appear on the top-left corner after adding constraints?


I'm developing an iOS application that has a Segue where some information is displayed. The information that I'm displaying is appearing in the middle of the Segue and I want it to appear right below the X or close button.

This is how the text is appearing and I want to appear right below the X button

I added the constraints necessary in the Storyboard and in the Storyboard I see it as I want it, but it's not translating when the application is ran. The text where I'm having problems can be seen in the picture below in the right, which is the Segue.

Auto-layout in Storyboard, I'm having problems with the label on the View Controller that's on the right

The following code snippet is meant to make the text start from the top left corner of the label text.

override func viewDidLoad() {
    super.viewDidLoad()

    infoLabel.text = text
    infoLabel.numberOfLines = 0;
    infoLabel.sizeToFit()
    
}

but after adding some constraints on that label to make it adapt to other screen sizes the text stopped starting on the top-left corner and started right in the middle-left corner. How can I fix this?


Solution

  • If you want to make label to constrain to right, don't give the leading constraint. Just the trailing, top constraints are enough for a label. Only give width constraint if you want label to take a fixed space.

    In your case, just delete the leading constraint.

    You can also play with the text alignment, set the text alignment to right if you want to keep your constraints intact.