Reputation: 129
I have a view that I initialise like this:
var view: UIView! = {
var perm = UIView()
perm.backgroundColor = UIColor.black
// enable auto layout
perm.translatesAutoresizingMaskIntoConstraints = false
return perm
}()
After that I add a label as a subview to view
. The label is initialised like this:
var title: UILabel! = {
let perm = UILabel()
perm.textColor = UIColor.white
perm.numberOfLines = 0
perm.font = UIFont.boldSystemFont(ofSize: 20)
// enable auto layout
perm.translatesAutoresizingMaskIntoConstraints = false
return perm
}()
After that I add programmatically some constraints. When I run the app the title
is displayed in the right position, but the view
's background color has not been set.
EDIT
This is how I've set the constraints:
view.addSubview(title)
view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: image.bottomAnchor).isActive = true
title.leadingAnchor.constraint(equalTo: title.superview!.leadingAnchor, constant: 20).isActive = true
title.trailingAnchor.constraint(equalTo: title.superview!.trailingAnchor, constant: -20).isActive = true
title.bottomAnchor.constraint(equalTo: title.superview!.bottomAnchor, constant: -20).isActive = true
Upvotes: 0
Views: 873
Reputation: 100533
view
needs a height
view.heightAnchor.constraint(equalToConstant:200).isActive = true
OR For label height plus top and bottom padding 40
title.topAnchor.constraint(equalTo:view.topAnchor, constant:20).isActive = true
Upvotes: 4