【发布时间】:2017-02-20 15:29:50
【问题描述】:
我正在尝试通过嵌套视图层次结构使用preservesSuperviewLayoutMargins,但在 UIKit 上遇到了很多问题,并且想知道我做错了什么(或者这是否是一个真正的错误)。
我正在尝试布置一些视图(一些并排,一些相互上方),如下所示:
// Various combinations here will create different visual results (it will either work or won't)
let i1 = ImageView()
//let i1 = LabelView()
let i2 = ImageView()
//let i2 = LabelView()
let i3 = ImageView()
//let i3 = LabelView()
let view = LeftRight(left: i1, right: TopBottom(top: i2, bottom: i3))
//let view = LeftRight(left: TopBottom(top: i2, bottom: i3), right: i1)
通过一些布局,我可以让它工作,如下所示。您可以看到右侧的图像正确缩进了绿色视图,而绿色视图又正确缩进了白色视图。
但与其他人一起我很挣扎:
在应用程序中运行与此类似的代码会导致完全锁定和内存失控。
使用layoutMargins 完成缩进,如下所示:
let masterView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
masterView.translatesAutoresizingMaskIntoConstraints = false
masterView.layoutMargins = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
let subView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
subView.translatesAutoresizingMaskIntoConstraints = false
subView.layoutMargins = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
这是来自游乐场的图像布局示例。 The full playground project can be found here 并且可以轻松加载并在 XCode 中运行以了解我的意思。
class ImageView: UIView {
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 1000, height: 1000))
self.preservesSuperviewLayoutMargins = true
self.layoutMargins = .zero
let imageView = UIImageView(image: UIImage(named: "jesus"))
imageView.contentMode = .center
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
self.clipsToBounds = true
imageView.backgroundColor = UIColor.red
self.addSubview(imageView)
imageView.leftAnchor.constraint(equalTo: self.layoutMarginsGuide.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: self.layoutMarginsGuide.rightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor).isActive = true
}
}
【问题讨论】:
-
我无法理解“其他”案例中的问题所在。您只向我们显示黑屏,但没有代码。你能补充一些细节吗?
-
代码都在操场上。太多了,所以我在这里只展示了基础知识。黑屏是因为布局系统似乎无法渲染!