Vale
Vale

Reputation: 17

How to add constraints to label?

so i created an array and placed it into a UILabel and now i want this label to stick to the top. but searching through the net this is all i could come up with:

let currentWeek = Date()

let weekDays = UILabel.init()
weekDays.frame = CGRect(x: 10, y: 65, width: 414, height: 25)
weekDays.text = "\(currentWeek.day())"
self.view.addSubview(weekDays)
weekDays.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
weekDays.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
weekDays.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
weekDays.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

according to some guide this set of constraints was supposed to make my label stretch to fill the whole screen. but even tho i didn't get any error warnings, it did't change the appearance of my label either.

Upvotes: 0

Views: 809

Answers (2)

Deep
Deep

Reputation: 436

Set the translatesAutoresizingMaskIntoConstraints of weekDays false.

weekDays.translatesAutoresizingMaskIntoConstraints = true

Upvotes: 0

PGDev
PGDev

Reputation: 24341

Set the translatesAutoresizingMaskIntoConstraints of weekDays as false, i.e.

weekDays.translatesAutoresizingMaskIntoConstraints = false

A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.

By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.

And add the height constraint to weekDays instead of the bottomAnchor, i,e.

weekDays.heightAnchor.constraint(equalToConstant: 100.0)

Upvotes: 1

Related Questions