iOS自动布局结果不正确

时间:2018-03-13 02:56:32

标签: ios swift autolayout

我有一个自定义视图,其中包含两个子视图,可以平分他们的超级视图。我想要如下所示的自定义视图:

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

但是,无论我修改约束,结果总是如下所示:

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

自定义视图的框架是正确的,它是(0,300,375,60)。但其子视图的起源始终为(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()
}

1 个答案:

答案 0 :(得分:0)

我错过了一个垂直约束,如下所示:

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)
  ])

  // ...
}

这将纠正我的问题。