我可以在使用 frame, bounds, autoresizingMask
定位自身的父 View 中添加自动布局 View 吗?
通常在互联网上你会看到相反的情况,但我无法实现这种情况。
编辑: 我已经为你们添加了一些代码。只需使用“Single View Application”创建一个新的 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使用的是Manual Layout,而custom和childView使用的是Autolayout。但结果是使用自动布局的 childView 没有显示在屏幕上,当我检查它时,我看到它的宽度为 0,高度为 0。
这就是我得到的,根本没有蓝色区域。
最佳答案
是的,但你必须非常小心并且相当有限。
从技术上讲,如果窗口中的任何 View 使用自动布局,则窗口中的所有内容都使用自动布局。只是对于 translatesAutoresizingMaskIntoConstraints
处于打开状态的 View ,约束是从 frame
和 autoresizingMask
自动生成的。
因此,您必须确保您的约束不会干扰那些自动生成的约束。您可以使用 translatesAutoresizingMaskIntoConstraints
将内容松散地“悬挂”在 View 之外,但您的约束不得“推”或“拉”这些 View 。使用 translatesAutoresizingMaskIntoConstraints
的 View 必须具有完全的移动和大小自由。
例如,您可以使用约束将按钮放置在距容器 View 前缘不远的位置,但如果您也约束到后缘,则最好优先考虑内容拥抱和抗压缩非常低,这样他们就不会试图改变容器的宽度。即便如此,您最终可能会遇到冲突。在自动布局中, View 的宽度不允许为负值。如果容器设置为零宽度并且按钮到边缘的距离不为零,那么这将是一个冲突。因此,对后缘的约束也应该具有低优先级,以便在必要时可以打破它。 (或者你可以为前沿做到这一点。)
您说您无法使用 translatesAutoresizingMaskIntoConstraints
在 View 中使用自动布局。如果您需要进一步的帮助,您需要解释您尝试了什么以及尝试时发生了什么。
关于ios - 手动布局中的自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30411278/