moh*_*945 7 objective-c ios autolayout swift
我可以在frame, bounds, autoresizingMask用于定位自身的父视图中添加自动布局视图吗?
通常在互联网上,您会看到相反的情况,但我无法实现这种情况。
编辑:我为你们添加了一些代码。只需使用“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)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
从代码中可以看出,子视图使用手动布局,而自定义和子视图使用自动布局。但结果是使用自动布局的 childView 没有显示在屏幕上,当我检查它时,我看到它的宽度为 0,高度为 0。
这就是我得到的,根本没有蓝色区域。

是的,但是你必须非常小心并且相当有限。
从技术上讲,如果窗口中的任何视图使用自动布局,则窗口中的所有内容都使用自动布局。只是约束是从frame和保留的autoresizingMask视图自动生成的。translatesAutoresizingMaskIntoConstraints
因此,您必须确保您的约束不会干扰那些自动生成的约束。您可以使用 来将内容松散地“悬挂”在视图上translatesAutoresizingMaskIntoConstraints,但您的约束不得“推”或“拉”这些视图。使用的视图translatesAutoresizingMaskIntoConstraints必须具有完全的移动和尺寸自由度。
例如,您可以使用约束将按钮定位在距离容器视图前缘较近的位置,但如果您也约束到后缘,则最好将内容拥抱和压缩阻力优先级设置得非常低,以便他们不会尝试改变容器的宽度。即便如此,你们最终还是可能会发生冲突。在自动布局中,视图的宽度不允许为负数。如果容器设置为零宽度并且按钮到边缘的距离非零,那么这将是冲突。因此,对后沿的约束也应该具有较低的优先级,以便在必要时可以打破它。(或者你可以为前沿做到这一点。)
您说您无法在视图中使用自动布局来实现translatesAutoresizingMaskIntoConstraints。如果您需要进一步的帮助,您需要解释您尝试过的操作以及尝试后发生的情况。
| 归档时间: |
|
| 查看次数: |
3341 次 |
| 最近记录: |