您可以使用UIStackView
,支持自動佈局。
這樣你imageViews將增長/收縮根據屏幕大小。而且你可以添加更多的imageViews到。堆棧更容易
下面是代碼:
class SomeViewController: UIViewController {
// MARK: Properties
let stack = UIStackView()
let imageView1 = UIImageView()
let imageView2 = UIImageView()
let imageView3 = UIImageView()
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
stack.axis = .Horizontal // can omit, default is .Horizontal
stack.alignment = .Center
stack.distribution = .Fill // can omit, default is .Fill
stack.spacing = 20 // spacing between image views
view.addSubview(stack)
imageView1.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.36)
imageView2.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
imageView3.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
button.setTitle("Boom", forState: .Normal)
button.backgroundColor = UIColor.blackColor()
view.addSubview(button)
stack.addArrangedSubview(imageView1)
stack.addArrangedSubview(imageView2)
stack.addArrangedSubview(imageView3)
// Constraints for stack
stack.translatesAutoresizingMaskIntoConstraints = false
stack.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 20).active = true
stack.leadingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.leadingAnchor).active = true
stack.trailingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.trailingAnchor).active = true
// Constraints for imageView1
imageView1.translatesAutoresizingMaskIntoConstraints = false
imageView1.widthAnchor.constraintEqualToAnchor(imageView2.widthAnchor, multiplier: 0.8).active = true // to make imageView1 smaller than the red one
imageView1.heightAnchor.constraintEqualToAnchor(imageView1.widthAnchor, multiplier: 1.5).active = true
// Constraints for imageView2
imageView2.translatesAutoresizingMaskIntoConstraints = false
imageView2.heightAnchor.constraintEqualToAnchor(imageView2.widthAnchor, multiplier: 1.5).active = true
// Constraints for imageView3
imageView3.translatesAutoresizingMaskIntoConstraints = false
imageView3.widthAnchor.constraintEqualToAnchor(imageView2.widthAnchor, multiplier: 0.65).active = true // to make imageView3 smaller than the red one
imageView3.heightAnchor.constraintEqualToAnchor(imageView3.widthAnchor, multiplier: 1.5).active = true
// Constraints for button
button.translatesAutoresizingMaskIntoConstraints = false
button.topAnchor.constraintEqualToAnchor(stack.bottomAnchor, constant: 50).active = true // spacing from the stack
button.leadingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.leadingAnchor).active = true
button.trailingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.trailingAnchor).active = true
}}
![enter image description here](https://i.stack.imgur.com/jtmHZ.png)
能否請你解釋一下就是Wo RKS?我不明白寬高比約束。請詳細說明您的答案,以便我可以學習。 – LuckyLuke