Ten*_*Jay 1 ios autolayout nslayoutconstraint visual-format-language swift
如何UIView使用自动布局和Apple的可视格式语言设置谁的大小和位置的宽度和高度?
这是代码(view只是变量UIViewController):
// Create and add the view
var stageView = UIView()
stageView.setTranslatesAutoresizingMaskIntoConstraints(false) // Since I'm using Auto Layout I turn this off
view.addSubview(stageView)
// Create and add constraints to the containing view
let viewsDictionary = ["stageView":stageView]
let horizontalConstraints: NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-150-[stageView]-150-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let verticalConstraints: NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[stageView]-150-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: viewsDictionary)
view.addConstraints(horizontalConstraints)
view.addConstraints(verticalConstraints)
println("stageView.frame=\(stageView.frame)")
Run Code Online (Sandbox Code Playgroud)
得到了:
stageView.frame=(0.0,0.0,0.0,0.0)
Run Code Online (Sandbox Code Playgroud)
所以我试过了:
let fittingSize = stageView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
println("fittingSize=\(fittingSize)")
Run Code Online (Sandbox Code Playgroud)
得到了:
fittingSize=(0.0,0.0)
Run Code Online (Sandbox Code Playgroud)
我似乎无法找到一种方法来获得大小.我可以stageView使用自动布局和可视化格式语言将子视图添加到该位置,但是我无法获得stageView需要进一步定位这些子视图的宽度和高度.
有任何想法吗?
你有几个选择:
您可以通过调用setNeedsLayout然后调用来强制布局引擎立即调整视图大小layoutIfNeeded.这是不推荐,因为它是效率低下,布局所需的任何手动帧可能没有尚未设置.您可以在我对这个问题的回答中详细了解这种方法.
您还可以等到视图控制器中的子视图更新:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
println("stageView.frame = \(stageView.frame)")
}
Run Code Online (Sandbox Code Playgroud)
如果你想知道一个UIView子类(或者更常见的是一个UITableViewCell子类,你可以在layoutSubviews运行后检查:
override func layoutSubviews() {
super.layoutSubviews()
println("self.frame = \(self.frame)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5592 次 |
| 最近记录: |