2016-01-23 74 views
0

Storyboard Screenshot如果我想以编程方式创建这些约束,我该怎么做?

我有这些约束一个UITableView。我试图以编程方式创建UITableView,但仍希望在代码中使用这些约束。

+0

见节 - > HTTPS:/ /developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW1 – Adrian

回答

2

你可以做到这一点比较用视觉语言的格式很简单:

添加您的看法,topLayoutGuidebottomLayoutGuide到字典。我用views。您还必须将translatesAutoresizingMaskIntoConstraints设置为false以使约束生效。

例子:

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[yourView]-(-15)-|", options: [], metrics: nil, views: views)) 
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayout][yourView][botLayout]", options: [], metrics: nil, views: views)) 
0

一种方式做的是:

let newView = UIView() 
newView.backgroundColor = UIColor.redColor() 
newView.translatesAutoresizingMaskIntoConstraints = false 
view.addSubview(newView) 


    let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0) 
view.addConstraint(horizontalConstraint) 

    let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -15) 
view.addConstraint(verticalConstraint) 

    let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) 
    view.addConstraint(widthConstraint) 

    let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) 
    view.addConstraint(heightConstraint) 

获取更多信息,您可以在这里遵循`NSLayoutConstraints`这个Swift | Adding constraints programmatically

相关问题