在Swift中,如何獲得在運行時使用自動佈局約束條件創建的UIView的寬度(或高度)?在運行時訪問UIView寬度
我試過view1.frame.size.width
和view1.frame.width
,但都返回0
。
我一直在下面通過MakeAppPie自動佈局教程,並添加view1.layer.cornerRadius = view1.bounds.width/2
如下,但是這並沒有影響,所以我做了保安view1.bounds.width
,得到了0
:
class ViewController: UIViewController {
func makeLayout() {
//Make a view
let view1 = UIView()
view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view1.backgroundColor = UIColor.redColor()
//Make a second view
let view2 = UIView()
view2.setTranslatesAutoresizingMaskIntoConstraints(false)
view2.backgroundColor = UIColor(red: 0.75, green: 0.75, blue: 0.1, alpha: 1.0)
//Add the views
view.addSubview(view1)
view.addSubview(view2)
//--------------- constraints
//make dictionary for views
let viewsDictionary = ["view1":view1,"view2":view2]
//sizing constraints
//view1
let view1_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view1(>=50)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let view1_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:[view1(50)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
view1.addConstraints(view1_constraint_H)
view1.addConstraints(view1_constraint_V)
//view2
let view2_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:[view2(50)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let view2_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:[view2(>=40)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
view2.addConstraints(view2_constraint_H)
view2.addConstraints(view2_constraint_V)
//position constraints
//views
let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-100-[view2]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-136-[view1]-100-[view2]-100-|", options: NSLayoutFormatOptions.AlignAllTrailing, metrics: nil, views: viewsDictionary)
view.addConstraints(view_constraint_H)
view.addConstraints(view_constraint_V)
view1.layer.cornerRadius = view1.bounds.width/2
}
override func viewDidLoad() {
super.viewDidLoad()
func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 1, alpha: 1.0)
makeLayout()
}
}
view1.frame.width應該可以工作。你能發佈更多的代碼嗎? – 2014-10-26 21:52:52
感謝您的回覆史蒂夫 - 添加了上面的代碼。 – gemello 2014-10-26 22:15:03
您在那裏獲得0,因爲此時自動佈局機制尚未開始調整視圖大小。 – JDS 2014-10-26 22:28:55