在运行时访问UIView宽度
在Swift中,如何获得在运行时使用自动布局约束条件创build的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() } }
添加这个,你很好去:
override func viewDidLayoutSubviews() { println(self.view1.frame.size) }
你可以随意看宽度或高度。
关于这些领域只是一件事情:
self.view1.frame.size.width self.view1.frame.size.height
只有实际的用户设备大小,如果视图已经绘制到屏幕上,否则他们是你在故事板中设置它们。 所以如果你在绘制视图之前试图进行某种计算,你将不得不以另一种方式来计算宽度或高度!
你只能用这个
self.view1.frame.size.width self.view1.frame.size.height