我正在尝试根据父视图的宽度将子视图放在左边距.这听起来很简单但我无法弄清楚如何使用autolayout来做到这一点.
从逻辑上讲,我只需要将左边距值设置为父宽度的某个百分比值,但此刻,我无法将该逻辑转换为自动布局.
这是我目前的代码:
var view = UIView(); view.backgroundColor = UIColor.redColor(); view.frame = CGRectMake(0,320,400); var sview = UIView(); sview.setTranslatesAutoresizingMaskIntoConstraints(false); sview.backgroundColor = UIColor.yellowColor(); //sview.frame = CGRectMake(0,50,50); view.addSubview(sview); var dict = Dictionary<String,UIView>() dict["Box"] = sview; var con1 = NSLayoutConstraint(item: sview,attribute: NSLayoutAttribute.Top,relatedBy: NSLayoutRelation.Equal,toItem: view,multiplier: 1.0,constant: 20.0); view.addConstraint(con1); var con2 = NSLayoutConstraint(item: sview,attribute: NSLayoutAttribute.Left,attribute: NSLayoutAttribute.Width,multiplier: 0.75,constant: 0.0); view.addConstraint(con2); var con3 = NSLayoutConstraint(item: sview,constant: 0.0); view.addConstraint(con3); var con4 = NSLayoutConstraint(item: sview,attribute: NSLayoutAttribute.Height,constant: 0.0); view.addConstraint(con4);
var con2 = NSLayoutConstraint(item: sview,constant: 0.0); view.addConstraint(con2);
错误:
* Terminating app due to uncaught exception ‘NSInvalidArgumentException’,reason: ‘* +[NSLayoutConstraint
constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]:
Invalid pairing of layout attributes’
有没有人知道如何实现这一目标?我只想让左边距为父视图宽度的0.75%.
谢谢.
解决方法
你想要的是sview的左边是在视图左边的某个点,你写的是你希望sview的左边是视图宽度的某个点,这不是一个正确的布局属性配对作为你的错误说.
这是你需要做的:
NSLayoutConstraint(item: sview,multiplier: 1,constant: (CGRectGetWidth(view.bounds) * 0.75));
希望能帮助到你!
编辑
我发现了一篇关于基于Percented的边距的精彩文章:http://simblestudios.com/blog/development/percentage-width-in-autolayout.html
甚至更简单:
http://simblestudios.com/blog/development/easier-percentage-width-in-autolayout.html