Center align Labels and images inside UIView programatically with Swift - ios

Im working on an app and came across a problem that I cant seem to solve.
I am making a uiview with labels and images inside it. The content needs to be centered inside the view.
The problem is that the label will hold different lenght texts and the view itself will have different width depending on where it is used.
Here is how it should look:
And here with longer text:
As you can see there should be 1 label to the left, one uiimage in the middle and another label to the right all centered to the middle even though the text length could be different.
This is what I have so far in code. I need to do this programatically if possible. Im running a method to create the button depending on a value.
func cost(cost:Int){
costView = UIView()
costView?.setTranslatesAutoresizingMaskIntoConstraints(false)
self.costView?.clipsToBounds = true
self.addSubview(costView!)
self.costLabel.frame = CGRectMake(0, 0, 60, self.bounds.size.height)
self.costLabel.textAlignment = NSTextAlignment.Right
self.costLabel.textColor = UIColor.whiteColor()
self.costLabel.font = Services.exoFontWithSize(16)
self.costLabel.text = String(cost)
costView?.addSubview(costLabel)
self.costBrainImageView = UIImageView(frame: CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.height))
self.costBrainImageView?.image = Graphics.maskImageNamed("CommonMediumBrain", color: UIColor.whiteColor())
self.costBrainImageView?.contentMode = UIViewContentMode.ScaleAspectFill
costView?.addSubview(costBrainImageView!)
self.label.adjustsFontSizeToFitWidth = true
self.label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.label.numberOfLines = 1
self.label.minimumScaleFactor = 0.20
self.label.textAlignment = NSTextAlignment.Right
self.label.font = Services.exoFontWithSize(20)
//Constraints
var viewsDict = Dictionary <String, UIView>()
viewsDict["label"] = label
viewsDict["brainView"] = costView
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[label]|", options: nil, metrics: nil, views: viewsDict))
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[brainView]|", options: nil, metrics: nil, views: viewsDict))
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[label]-5-[brainView]-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: viewsDict))
}
For the moment this breaks since this line
NSLayoutFormatOptions.AlignAllCenterX
'Unable to parse constraint format:
Options mask required views to be aligned on a horizontal edge, which is not allowed for layout that is also horizontal.
H:|-[label]-5-[brainView]-|
If i remove that everything is aligned to the left and not centered but im not sure this is the right way to accomplish what i want to do.
Any clues on how to solve this?
Thanks for any help

Firstly, change .AlignAllCenterX to .AlignAllCenterY, the reason is that"H:|-[label]-5-[brainView]-|" specifies how views position horizontally, you want label and brainView to have the same center Y position.
Secondly, make a subview that contains all 3 views, then center this subview inside the black rectangle. You can use costView as the subview.
Below is some modified code based on your existing code.
costView!.addSubview(label)
//Constraints
var viewsDict = Dictionary <String, UIView>()
viewsDict["label"] = label
viewsDict["brainView"] = costBrainImageView
viewsDict["costLabel"] = costLabel
costView!.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[label]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[brainView]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[costLabel]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[label]-5-[brainView]-5-[costLabel]-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: viewsDict))
costView!.backgroundColor = UIColor.redColor()
// center costView inside self
let centerXCons = NSLayoutConstraint(item: costView!, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0);
let centerYCons = NSLayoutConstraint(item: costView!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0);
self.addConstraints([centerXCons, centerYCons])

Related

NSLayoutConstraints with visual format doesn't work as expected when in UIScrollView? [duplicate]

This question already has answers here:
UIScrollView doesn't use autolayout constraints
(4 answers)
scroll view not scrolling vertically
(2 answers)
Closed 4 years ago.
I am putting a UILabel inside a UIScrollView, I'd like to add these constraints to the label:
Top margin is 20
Left margin is 20
Right margin is 20
Label's height is 40
Here's the code I wrote for these constraints using visual format:
let label = UILabel.init(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Some Text"
scrollView.addSubview(label)
let horizontalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-20-[label]-20-|",
options: [],
metrics: nil,
views: ["label": label]
)
let verticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-20-[label(40)]",
options: [],
metrics: nil,
views: ["label": label]
)
NSLayoutConstraint.activate(horizontalConstraints + verticalConstraints)
But this picture is what I'm getting (can't upload photo because I have low reputations). I added borders to the views, the blue one is the border of UIScrollView, the red one is the border of the UILabel
Your code isn't correct. Here is how your code should looks. And if you use this way of adding constraints, you don't need to activate constraints with special method. These vertical and horizontal constraints have already activated.
//horizontal constraints
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|",
options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": label]))
//vertical constraints
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[v0(40)]",
options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": label]))
Explanation of syntax:
"H", "V" - horizontal, vertical constraints
"|" - anchor, for example "H:|[v0]" - left anchor
"-20-" - offset, for example "V:|-20-[v0]" - top anchor with offset 20
"[v0(40)]" - this is the size of view, for example "V:[v0(40)]" - height is 40
"[v0]" - your first view in visual format. This format can set constraints for several views.
For example:
(format: "V:|-16-[v0]-8-[v1(44)]-16-[v2(1)]|", views: ["v0": firstView], ["v1": secondView], ["v2": thirdView])
I figured out. Although I do not know why this happens, whether it's a bug with UIScrollView or things just have to be done this way.
Apparently, when you add subviews to a UIScrollView in Story Board, you'll always get a warning saying that the position of the subviews are ambiguous. So, what you would do is to add a UIView to the scroll view and add these constraints to it:
Top = 0, Leading = 0, Trailing = 0 and Bottom = 0
UIView is centered both horizontally and vertically in the scroll view
After that, you're good to add subviews to UIView without getting those warnings.
Same reason applies here, when you want to add subviews to a UIScrollView programmatically, and also set up some constraints, you should put a UIView inside the scroll view and put all subviews inside the UIView:
let subviewContainer = UIView.init(frame: .zero)
subviewContainer.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(subviewContainer)
var constraints: [NSLayoutConstraint] = []
// Step 1, set up horizontal constraints to make leading & trailing = 0
constraints += NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[subviewContainer]-0-|",
options: [],
metrics: nil,
views: ["subviewContainer": subviewContainer]
)
// Step 2, set up vertical constraints to make top & bottom = 0
constraints += NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[subviewContainer]-0-|",
options: [],
metrics: nil,
views: ["subviewContainer": subviewContainer]
)
// **Step 3, center "subviewContainer" horizontally & vertically in scroll view**
constraints.append(
NSLayoutConstraint.init(
item: subviewContainer,
attribute: .centerX,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerX,
multiplier: 1,
constant: 0
)
)
constraints.append(
NSLayoutConstraint.init(
item: subviewContainer,
attribute: .centerY,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerY,
multiplier: 1,
constant: 0
)
)
// Step 4, activate all constraints
NSLayoutConstraint.activate(constraints)
After these 4 steps, you are now good to add subviews to "subviewContainer".

How do I put two views at the same position using "auto layout visual format"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to put two views at the same position using "auto layout visual format" in Swift, how do I do that in an elegant way?
I succeeded using NSLayoutConstraint, but I hope I can still find an elegant way using visual format.
My code using NSLayoutConstraint:
NSLayoutConstraint(item: greenView, attribute: .Left, relatedBy: .Equal, toItem: redView, attribute: .Left, multiplier: 1.0, constant: 0).active = true
NSLayoutConstraint(item: greenView, attribute: .Top, relatedBy: .Equal, toItem: redView, attribute: .Top, multiplier: 1.0, constant: 0).active = true
NSLayoutConstraint(item: greenView, attribute: .Right, relatedBy: .Equal, toItem: redView, attribute: .Right, multiplier: 1.0, constant: 0).active = true
NSLayoutConstraint(item: greenView, attribute: .Bottom, relatedBy: .Equal, toItem: redView, attribute: .Bottom, multiplier: 1.0, constant: 0).active = true
I would echo what vacawama said in his excellent answer about using layout anchors. It's probably as clear and elegant as you get with the native API, but please note that it requires iOS 9 and later.
For the purpose of code organization, I'd like to suggest instead of looking for terser code, organize your code into methods and/or extensions, for example:
extension UIView {
func constraintsAligningAllEdges(toView view2: UIView) -> [NSLayoutConstraint] {
return [ topAnchor.constraintEqualToAnchor(view2.topAnchor),
bottomAnchor.constraintEqualToAnchor(view2.bottomAnchor),
leadingAnchor.constraintEqualToAnchor(view2.leadingAnchor),
trailingAnchor.constraintEqualToAnchor(view2.trailingAnchor) ]
}
}
Using it would look like this:
NSLayoutConstraint.activateConstraints(greenView.constraintsAligningAllEdges(toView: redView))
...or perhaps make that a class function extension for NSLayoutConstraint.
On the topic of Visual Format Language, vacawama also brought up a very interesting use of the layout options. Here's another possible way of achieving the same goal:
let views = ["greenView" : greenView, "redView" : redView]
NSLayoutConstraint.activateConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:[greenView]-(0#1)-[redView]", options: [.AlignAllTop, .AlignAllBottom], metrics: nil, views: views) +
NSLayoutConstraint.constraintsWithVisualFormat("V:[greenView]-(0#1)-[redView]", options: [.AlignAllLeading, .AlignAllTrailing], metrics: nil, views: views)
)
What I've done here is instead of introducing extra views, I've introduced two extraneous constraints, one between green bottom & red top, another one between green trailing & top leading. They both have the lowest priority of 1 however, so as you would normally have other constraints deciding the size/position of either view, they should cause no harm.
Is this somewhat more elegant? I don't know, but personally I think layout anchors make more sense to me, and third-party frameworks like SnapKit are also fine options.
The Visual Format Language can't be used for every possible case. I believe aligning the two views to each other is such a case.
I would suggest you use layout anchors instead, like this:
override func viewDidLoad() {
super.viewDidLoad()
let redView = UIView()
redView.backgroundColor = .redColor()
redView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(redView)
let greenView = UIView()
greenView.backgroundColor = .greenColor()
greenView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(greenView)
let redHoriz = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[redView]-20-|", options: [], metrics: nil, views: ["redView": redView])
NSLayoutConstraint.activateConstraints(redHoriz)
let redVert = NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[redView]-50-|", options: [], metrics: nil, views: ["redView": redView])
NSLayoutConstraint.activateConstraints(redVert)
// Set greenView to occupy same space as the redView
greenView.leftAnchor.constraintEqualToAnchor(redView.leftAnchor).active = true
greenView.rightAnchor.constraintEqualToAnchor(redView.rightAnchor).active = true
greenView.topAnchor.constraintEqualToAnchor(redView.topAnchor).active = true
greenView.bottomAnchor.constraintEqualToAnchor(redView.bottomAnchor).active = true
}
The Visual Format Language allows you to align parts of views. For instance, you can align the tops of bottoms of two views by passing [.AlignAllTop, .AlignAllBottom] as the options argument of constraintsWithFormat. But, you can only align values that are perpendicular to the direction of the visual format. So, if you are specifying a horizontal layout, then you can align the tops and bottoms of the views. If you are specifying a vertical layout, then you can align the lefts and rights.
You can align two views by introducing two additional views. In the example below, the blue view picks up the top and bottom alignment of the red view, and the yellow view picks up the left and right alignment of the red view. Then the green view gets aligned to the top and bottom of the blue view and the left and right of the yellow view, thus it is aligned to the red view.
Finally, hiding the blue and yellow views leaves you with the setup you desire.
let redView = UIView()
redView.backgroundColor = .redColor()
redView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(redView)
let greenView = UIView()
greenView.backgroundColor = .greenColor()
greenView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(greenView)
let blueView = UIView()
blueView.translatesAutoresizingMaskIntoConstraints = false
blueView.backgroundColor = .blueColor()
blueView.hidden = true
view.addSubview(blueView)
let yellowView = UIView()
yellowView.translatesAutoresizingMaskIntoConstraints = false
yellowView.backgroundColor = .yellowColor()
yellowView.hidden = true
view.addSubview(yellowView)
let redHoriz = NSLayoutConstraint.constraintsWithVisualFormat("H:|-80-[redView]-80-|", options: [], metrics: nil, views: ["redView": redView])
NSLayoutConstraint.activateConstraints(redHoriz)
let redVert = NSLayoutConstraint.constraintsWithVisualFormat("V:|-80-[redView]-80-|", options: [], metrics: nil, views: ["redView": redView])
NSLayoutConstraint.activateConstraints(redVert)
let blueHorizVert = NSLayoutConstraint.constraintsWithVisualFormat("H:[redView][blueView]|", options: [.AlignAllTop, .AlignAllBottom], metrics: nil, views: ["redView": redView, "blueView": blueView])
NSLayoutConstraint.activateConstraints(blueHorizVert)
let yellowHorizVert = NSLayoutConstraint.constraintsWithVisualFormat("V:[redView][yellowView]|", options: [.AlignAllLeft, .AlignAllRight], metrics: nil, views: ["redView": redView, "yellowView": yellowView])
NSLayoutConstraint.activateConstraints(yellowHorizVert)
let greenTopBottom = NSLayoutConstraint.constraintsWithVisualFormat("H:[greenView][blueView]|", options: [.AlignAllTop, .AlignAllBottom], metrics: nil, views: ["greenView": greenView, "blueView": blueView])
NSLayoutConstraint.activateConstraints(greenTopBottom)
let greenLeftRight = NSLayoutConstraint.constraintsWithVisualFormat("V:[greenView][yellowView]|", options: [.AlignAllLeft, .AlignAllRight], metrics: nil, views: ["greenView": greenView, "yellowView": yellowView])
NSLayoutConstraint.activateConstraints(greenLeftRight)
So you can do it with VFL, but it isn't elegant. I would suggest you stick with using anchors.

How to programmatically add an InputAccessoryView with Autolayout?

I am trying to add a UIView with "Done" button as an input accessory view to the text field.
let view = UIView()
let doneButton = UIButton(type: .Custom)
doneButton.setTitle("Done", forState: .Normal)
doneButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(doneButton)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[button]-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["button":doneButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button]|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["button":doneButton]))
view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: doneButton, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)) // Even this does not work
self.emailTextField.inputAccessoryView = view
But however I cannot see the views height being set nor the buttons in the View Hierarchy debugger/inspector in Xcode.
But if I add a view by setting its frame I can see the view being added.
Also I tried setting height constraint forcibly to a constant 21 and it broke some other constraints which I had not added _UIKBAutolayoutHeightConstraint
"<NSLayoutConstraint:0x7fa3c962be50 UIView:0x7fa3c963bf60.height == UIButton:0x7fa3c963c0d0.height + 21>",
"<NSLayoutConstraint:0x7fa3c95e0a90 '_UIKBAutolayoutHeightConstraint' V:[UIView:0x7fa3c963bf60(0)]>"
Any one faced this issue before ?
Swift 3+
You need to specify size of toolbar view in first line.
Don't use 'view' as variable in viewcontroller class since it creates confusion vs self.view
override func viewDidLoad() {
super.viewDidLoad()
let toolBar = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 50))
toolBar.backgroundColor = .gray
let doneButton = UIButton(type: .custom)
doneButton.setTitle("Done", for: .normal)
doneButton.translatesAutoresizingMaskIntoConstraints = false
toolBar.addSubview(doneButton)
toolBar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[button]-|",
options: .directionLeadingToTrailing,
metrics: nil,
views: ["button":doneButton]))
toolBar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[button]|",
options: .directionLeadingToTrailing,
metrics: nil,
views: ["button":doneButton]))
self.emailTextField.inputAccessoryView = toolBar
}

VFL constraints in swift: Crashes due to no superview

I'm trying to do a simple layout programmatically and I'm missing something simple, or have something out of place, I think. The following ViewController should center the label in the super view. However, it crashes with this trimmed message: The view hierarchy is not prepared for the constraint ... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled... View not found in container hierarchy: ... That view's superview: NO SUPERVIEW The other SO questions with this error message are using nibs for the most part, and I'm tring to avoid that, or use Obj-C instead of swift. This question deals with the topic a bit but is a bit old.
Can anyone point me in the right direction?
class ViewController: UIViewController {
let label1 = UILabel() as UILabel
func layoutView(){
label1.text = "Click to see device configuration"
label1.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label1)
let viewsDictionary = ["label1":label1]
let label1_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label1]-|",
options: NSLayoutFormatOptions(0),
metrics: nil,
views: viewsDictionary)
let label1_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label1]-|",
options: NSLayoutFormatOptions(0),
metrics: nil, views:
viewsDictionary)
label1.addConstraints(label1_H) // Comment these 2 lines and it runs, but
label1.addConstraints(label1_V) // of course the label is upper left
}
override func viewDidLoad() {
super.viewDidLoad()
layoutView()
}
}
Those constraints are made between the label and its superview. The constraints should be added to that superview, not to the label.
You're almost there. Just replace the following lines...
label1.addConstraints(label1_H) // Comment these 2 lines and it runs, but
label1.addConstraints(label1_V) // of course the label is upper left
... with the following code:
view.addConstraints(label1_H) // Comment these 2 lines and it runs, but
view.addConstraints(label1_V) // of course the label is upper left
However, the constraints H:|-[label1]-|" and V:|-[label1]-|" are equivalent to H:|-8-[label1]-8-|" and V:|-8-[label1]-8-|" (see the iOS Developer Library for more details on default margins). Thus, those constraints are not meant to center your label. In fact, you will just have an enormous label that has 8 unit top, leading, trailing and bottom margins to the viewController's view.
Add the following line of code in your layoutView() method to see what I mean:
label1.backgroundColor = UIColor.orangeColor()
It can be OK but if you really want to center your label, you will have to use the following code:
func layoutView() {
label1.text = "Click to see device configuration"
label1.backgroundColor = UIColor.orangeColor()
//Set number of lines of label1 to more than one if necessary (prevent long text from being truncated)
label1.numberOfLines = 0
label1.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label1)
let xConstraint = NSLayoutConstraint(item: label1,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1.0,
constant: 0.0)
self.view.addConstraint(xConstraint)
let yConstraint = NSLayoutConstraint(item: label1,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1.0,
constant: 0)
self.view.addConstraint(yConstraint)
//Add leading and trailing margins if necessary (prevent long text content in label1 to be larger than screen)
let viewsDictionary = ["label1" : label1]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=10#750)-[label1]-(>=10#750)-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary))
}

UISegmentedControl is hidden under the titleBar

i guess i am missing something with the UISegmentedControl and auto layout.
i have a TabbedApplication (UITabBarController), and i created a new UIViewController to act as tab.
to the new view i added UISegmentedControl, and place it to top using auto layout.
i guess i don't understand completely something ,
cause the UISegmentedControl is hiding under the titleBar
. can u help me understand what i am missing ?
thank you .
import Foundation
import UIKit;
class ViewLikes:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "some title";
var segmentControl:UISegmentedControl = UISegmentedControl(items:["blash", "blah blah"]);
segmentControl.selectedSegmentIndex = 1;
segmentControl.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(segmentControl)
//Set layout
var viewsDict = Dictionary <String, UIView>()
viewsDict["segment"] = segmentControl;
//controls
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segment]-|",
options: NSLayoutFormatOptions.AlignAllCenterX,
metrics: nil,
views: viewsDict))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[segment]",
options: NSLayoutFormatOptions(0),
metrics: nil,
views: viewsDict))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your top space vertical constraint has to be related to your Top Layout Guide, not to your container margin. The following code should fix this problem:
override func viewDidLoad() {
super.viewDidLoad()
let segmentControl = UISegmentedControl(items:["blash", "blah blah"])
segmentControl.selectedSegmentIndex = 1
segmentControl.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(segmentControl)
//Horizontal constraints
view.addConstraint(NSLayoutConstraint(item: segmentControl, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
//Horizontal constraints
let viewsDict = ["segment" : segmentControl]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segment]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
}
Note that the horizontal constraints setting has also been rewritten.

Resources