In Swift, how do I get the width (or height) at runtime, of a UIView that's created programmatically using auto layout constraints?
I've tried view1.frame.size.width
and view1.frame.width
, but both return 0
.
I've been following an auto layout tutorial by MakeAppPie and added view1.layer.cornerRadius = view1.bounds.width/2
as below, but this had no effect, so I did a po on view1.bounds.width
and got 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()
}
}