与视觉布局约束相对应的代码是什么?我想将其转换为NSLayoutConstraint.activate([])
格式。
scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
stackView = UIStackView()
scrollView.addSubview(stackView)
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
答案 0 :(得分:2)
视觉格式语言(VFL)可以同时创建多个约束,而这些约束确实可以。前三个VFL分别创建2个约束,最后一个创建一个约束。
我建议使用布局锚创建约束。这等效于您使用NSLayoutConstraint.activate()
和布局锚点的代码:
scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
stackView = UIStackView()
scrollView.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor)
])
注释:
.alignAllCenterX
对由此产生的约束的影响,在这种情况下,该选项没有任何作用。NSLayoutConstraint.activate()
调用中。我认为通过两次调用就更清楚了,因为每组都有一个目的。NSLayoutConstraint.activate()
很聪明,它为适当的视图添加了约束。它是首选,自iOS 8起已提供。stackView.translatesAutoresizingMaskIntoConstraints = false
和stackView.axis = .vertical
。 (您可能只是把那些问题排除在外,以使其更简洁)。