我试图在Swift中以编程方式使用autolayout。但是我有一个问题。我希望我的view1(红色框)与superview(H:| - [view1] - |)“有一个规则的间距对齐。这适用于右对齐而不是左边。我想要视图的左侧与右侧具有相同的间距。视图似乎想要与下面的按钮水平对齐。是否有人知道如何解决这个或我做错了什么?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "yolo"
let frame = UIScreen.mainScreen().bounds
var b = UIButton.buttonWithType(UIButtonType.System) as! UIButton
b.frame = CGRectMake(frame.minX + 50, frame.minY + 100, frame.width * 0.8, frame.height * 0.2)
b.backgroundColor = UIColor.purpleColor()
b.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
b.layer.cornerRadius = 17
b.setTitle("hello", forState: UIControlState.Normal)
b.setTranslatesAutoresizingMaskIntoConstraints(false)
// Do any additional setup after loading the view, typically from a nib.
let view1 = UIView()
view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view1.backgroundColor = UIColor.redColor()
let view2 = UIView()
view2.setTranslatesAutoresizingMaskIntoConstraints(false)
view2.backgroundColor = UIColor.yellowColor()
self.view.addSubview(b)
self.view.addSubview(view1)
// dictionary for views
let viewsDictionary = ["view1":view1,"view2":view2, "b":b]
let button_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[b(>=200)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let button_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:[b(>=200)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
b.addConstraints(button_constraint_H as [AnyObject])
b.addConstraints(button_constraint_V as [AnyObject])
//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 as [AnyObject])
view1.addConstraints(view1_constraint_V as [AnyObject])
let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[view1]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-90-[view1]-[b]-0-|", options: NSLayoutFormatOptions.AlignAllLeading, metrics: nil, views: viewsDictionary)
let view_constraint_H2:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|[b]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
view.addConstraints(view_constraint_H2 as [AnyObject])
view.addConstraints(view_constraint_V as [AnyObject])
view.addConstraints(view_constraint_H as [AnyObject])
}
答案 0 :(得分:1)
问题是你的约束毫无意义。你这么说:
"H:[view1(50)]"
"H:|-[view1]-|"
一方面,您希望view1
与其超级视图的边距对齐(这是-
的意思),但另一方面,您希望view1
成为(50)
正好50个点(这就是(new UploadPhotoFragment()).show(getFragmentManager(), null);
的含义)。你不能同时拥有这两个!