我能否在使用frame,bounds,autoresizingMask
定位的父视图中添加使用autolayout的子视图?
通常情况下,我们看到的是相反的情况,但我无法实现这种情况。
编辑: 我为大家添加了一些代码。只需创建一个新的Xcode项目并在为我们创建的ViewController.swift上粘贴以下代码即可。
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let custom = CustomManualLayoutSubviews()
let subview = UIView()
let childView = UIView()
custom.backgroundColor = UIColor.red
subview.backgroundColor = UIColor.green
childView.backgroundColor = UIColor.blue
custom.translatesAutoresizingMaskIntoConstraints = false
subview.translatesAutoresizingMaskIntoConstraints = false
childView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(custom)
custom.addSubview(subview)
subview.addSubview(childView)
pin(child: custom, parent: view)
pin(child: childView, parent: subview)
}
private func pin(child: UIView, parent: UIView) {
parent.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[view]-10-|", options: [], metrics: nil, views: ["view" : child]))
parent.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[view]-10-|", options: [], metrics: nil, views: ["view" : child]))
}
}
class CustomManualLayoutSubviews : UIView
{
override func layoutSubviews() {
super.layoutSubviews()
for subview in subviews {
subview.frame = bounds.insetBy(dx: 10, dy: 10)
print("subview frame: \(subview)")
}
}
}
从代码中可以看出,subview使用了手动布局而custom和childView使用了自动布局。但结果是使用自动布局的childView未显示在屏幕上,检查后发现其宽度和高度均为0。
如图所示,没有任何蓝色区域显示。
subview.translatesAutoresizingMaskIntoConstraints = false
将解决你的问题。这行代码阻止了CustomManualLayoutSubviews.layoutSubviews()
的生效。 - DawnSong