Go to google (or your favorite search engine) and search for swift add constraints programmatically
. This is very, very basic.
Here's a simple example:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create image view
let imgView = UIImageView()
imgView.backgroundColor = .systemYellow
// create image
let img = UIImage(systemName: "person.fill")
imgView.image = img
// add imageView to view
view.addSubview(imgView)
// use auto-layout
imgView.translatesAutoresizingMaskIntoConstraints = false
// respect safe area
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain imageView width to view safe-area width
imgView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
imgView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// aquare image view (1:1 ratio)
imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor),
// center vertically
imgView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
])
}
}
Result:
Edit - second example... Top third, centered horizontally:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(true, animated: false)
// create image view
let imgView = UIImageView()
imgView.backgroundColor = .systemYellow
// create image
let img = UIImage(systemName: "person.fill")
imgView.image = img
// add imageView to view
view.addSubview(imgView)
// use auto-layout
imgView.translatesAutoresizingMaskIntoConstraints = false
// respect safe area
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// you want the image view at the top?
imgView.topAnchor.constraint(equalTo: g.topAnchor),
// one-third of the height of the view?
imgView.heightAnchor.constraint(equalTo: g.heightAnchor, multiplier: 1.0 / 3.0),
// you want a aquare image view (1:1 ratio)?
imgView.widthAnchor.constraint(equalTo: imgView.heightAnchor),
// you want it centered horizontally?
imgView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
])
}
}
On iPhone 8:
On iPhone 12:
On 9.7" iPad Pro, landscape orientation:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…