Search code examples
iosswiftautolayout

iOS autolayout result is not correct


I have a customized view with two subviews which divide their superview equally. I want the customized view shown below:

-------------------------------
|              |              |
|             300             |
|              |              |
|-----------------------------|
|    red       |     green    |
|-----------------------------|
|                             |

However, whatever I modify the constraints, the result always show like below:

-------------------------------
|    red       |     green    |
|-----------------------------|
|                             |

The frame of customized view is correct, and it is (0, 300, 375, 60). But the origin of its subview is always (0, -300).

RootController.swift

override func viewDidLoad() {
  super.viewDidLoad()

  let view = RootView()
  view.translatesAutoresizingMaskIntoConstraints = false
  self.view.addSubview(view)
  self.rootView = view

  NSLayoutConstraint.activate([
    NSLayoutConstraint.constraints(withVisualFormat: "V:|-300-[v(60)]", metrics: nil, views: ["v": self.rootView!]),
    NSLayoutConstraint.constraints(withVisualFormat: "H:|[v]|", metrics: nil, views: ["v": self.rootView!])
  ].flatMap({ $0 }))
}

RootView.swift

override init (frame: CGRect) {
  super.init(frame: frame)

  var view = UIView()
  view.translatesAutoresizingMaskIntoConstraints = false
  view.backgroundColor = .red
  self.addSubview(view)
  self.red = view

  view = UIView()
  view.translatesAutoresizingMaskIntoConstraints = false
  view.backgroundColor = .green
  self.addSubview(view)
  self.green = view
}

override func updateConstraints () {
  NSLayoutConstraint.activate([
    NSLayoutConstraint.constraints(withVisualFormat: "H:|[r][g(==r)]|", metrics: nil, views: ["r": self.red, "g": self.green])
  ].flatMap({ $0 }))
  NSLayoutConstraint.activate([
    self.red.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.green.heightAnchor.constraint(equalTo: self.heightAnchor)
  ])
  super.updateConstraints()
}

Solution

  • I have missed one vertical constraint which is shown below:

    override func updateConstraints () {
      // ...
    
      NSLayoutConstraint.activate([
        self.red.heightAnchor.constraint(equalTo: self.heightAnchor),
        self.green.heightAnchor.constraint(equalTo: self.heightAnchor),
        self.red.topAnchor.constraint(equalTo: self.topAnchor),
        self.green.topAnchor.constraint(equalTo: self.topAnchor)
      ])
    
      // ...
    }
    

    This will correct my issue.