import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
setup()
}
private func setup() {
let container = UIView()
container.backgroundColor = .red
view.addSubview(container)
container.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
container.heightAnchor.constraint(equalToConstant: 100.0),
container.widthAnchor.constraint(equalToConstant: 100.0)
])
let label = UILabel()
label.text = "This is my text.This is my text.This is my text.This is my text.This is my text.This is my text.This is my text."
label.numberOfLines = 0
label.sizeToFit()
container.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.widthAnchor.constraint(equalTo: container.widthAnchor)
])
}
}
I have a 100x100 UIView
inside of which I want to add a UILabel
. UILabel
overflows the UIView
. I want to know how I can contain UILabel
inside UIView
without overflowing?
I tried,
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: container.topAnchor),
label.bottomAnchor.constraint(equalTo: container.bottomAnchor),
label.widthAnchor.constraint(equalTo: container.widthAnchor)
])
But this for some reason adds vertical padding,
And activating those constraints also has another problem and that is when the text length is small, the text is vertically centered. I want to pin it to top left always.