我有一个自定义 View ,其中有两个 subview ,它们平分其 super View 。我想要如下所示的自定义 View :
-------------------------------
| | |
| 300 |
| | |
|-----------------------------|
| red | green |
|-----------------------------|
| |
但是,无论我修改约束,结果总是如下所示:
-------------------------------
| red | green |
|-----------------------------|
| |
自定义 View 的框架是正确的,为(0, 300, 375, 60)。但其 subview 的原点始终为 (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()
}
最佳答案
我错过了一个垂直约束,如下所示:
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)
])
// ...
}
这将解决我的问题。
关于iOS 自动布局结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247593/