How to center multiple elements inside UIView - swift

I'm trying to center multiple elements (labels and buttons) inside UIView (or UIStackView). I tried adding elements to UIStackView with Center Alignment and Distribution Fill and Spacing 10, but my elements keeps getting positioned from the left side. I tried changing centers. Still no luck.
What i'm trying to achieve:
[-------label--button-------] With 2 elements.
[--label--button--button--] With 3 elements.
Is there any way of achieving this without using spacers. Theoretically I maybe could use constrains, but i'm not sure it's a good idea because of changing number of elements.
let simpleView = UIView()
simpleView.addSubview(text)
simpleView.addSubview(button)
let leftLeading = NSLayoutConstraint(item: text, attribute:
.LeadingMargin, relatedBy: .Equal, toItem: simpleView,
attribute: .LeadingMargin, multiplier: 1.0,
constant: 10)
let leftLeading2 = NSLayoutConstraint(item: button, attribute:
.LeadingMargin, relatedBy: .Equal, toItem: simpleView,
attribute: .LeadingMargin, multiplier: 1.0,
constant: 10)
simpleView.addConstraint(leftLeading)
simpleView.addConstraint(leftLeading2)
simpleView.translatesAutoresizingMaskIntoConstraints = false
simpleView.sizeToFit()
newView.addSubview(simpleView)
let horizontalConstraint = NSLayoutConstraint(item: simpleView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
newView.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: simpleView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
newView.addConstraint(verticalConstraint)
I must be doing something wrong because this is what I get (newView is red, button is blue, text label is missing) :

Create a view, center the view where you need to. Then inside that view you can insert each element and give each one a programatic NSLayoutConstraint that has a .Leading of 5 or whatever spacing you want between elements.
VIEW[ELEMENT ELEMENT ELEMENT]
The number will not matter. Look into NSLayoutConstraints and make sure you use view.addConstraints.

Related

How we set constraint for adding subview

I want to add view on my View, but they are not set well this width stretch. I am new to iOS. Any help would be appreciated. This is what I get when I try to do what I want, can someone help to fix this:
openView.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: openView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: openView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: openView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: openView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
self.view.addSubview(openView)
openView.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
openView.layoutIfNeeded()
In your xcode open main.Storyboard --> Open your viewController -->Add UIView --> Make your view frame like you want --> And add constraints
Ex: If you want width=600 & height=600, set frame like you want and then assign constraints.
.Refer linked image for reference
Here you are setting subview's frame as the initial frame of controller view. ie, the controller's view will be fully covered by subview.
If you want to add constraints,
1) Take the storyboard or xib.
2) Tap on the UI element.
3) Tap on the constraints button as shown in image.
4) Set the values from each border.
You can also set height, width such like parameters. The whole need is the system should be able to interpret the accurate position from the constraints.

How to add equal width and equal height constraints programmatically in swift?

Could anyone help me I have this simple view that is very simple to do if I'm using story board but all of my UILabel is based on somewhere(API) that is why I need to create my view programmatically.
this is the view I would like to achieved
what I accomplished at the moment are pinning the top label in its position and adding leading space on label 1, 2, & 3
basically what i need are:
pin the label 1 to the top label
pin the label 3 to bottom
add vertical spaces to label 1,2,3
have equal width and height constraint in label 1,2 ,3
this is my code so far.
private func addTopConstraint(from:AnyObject,to:AnyObject,cons:CGFloat){
let topConstraint = NSLayoutConstraint(item: from, attribute: .Top, relatedBy: .Equal, toItem: to, attribute: .Bottom, multiplier: 1.0, constant: cons)
self.view.addConstraint(topConstraint)
}
private func addVerticalSpace(from:AnyObject,to:AnyObject,cons:CGFloat){
let verticalSpace = NSLayoutConstraint(item: from, attribute: .Bottom, relatedBy: .Equal, toItem: to, attribute: .Bottom, multiplier: 1.0, constant: cons)
self.view.addConstraint(verticalSpace)
}
private func addLeadingSpace(from:AnyObject,to:AnyObject,cons:CGFloat){
let leadingSpace = NSLayoutConstraint(item: from, attribute: .Leading, relatedBy: .Equal, toItem: to, attribute: .Leading, multiplier: 1.0, constant: cons)
self.view.addConstraint(leadingSpace)
}
private func sameWidthAndHeight (from:AnyObject,to:AnyObject){
let width = NSLayoutConstraint(item: from, attribute: .Width, relatedBy: .Equal, toItem: to, attribute: .Width, multiplier: 1.0, constant: 0)
let height = NSLayoutConstraint(item: from, attribute: .Height, relatedBy: .Equal, toItem: to, attribute: .Height, multiplier: 1.0, constant: 0)
self.view.addConstraint(width)
self.view.addConstraint(height)
}
but the sameWidthAndHeight and addVerticalSpace function fails
maybe it something to do with content hugging and priorities too, I'm not that sure since we're used to do this in storyboard.
could anyone share a thought? Thanks in advance

Adding constraints programmatically in UIView with UITextView

I added constraints programmatically in my UITextView, but trailing and bottom constraints are not working correctly. others work fine.
I think UITextView frame size is not correct.
I just want to add margin in my UITextView programmatically.
My code is
let textView = UITextView()
self.view.addSubview(textView)
var constraints = [NSLayoutConstraint]()
constraintTop = NSLayoutConstraint(item: textView,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Top,
multiplier: 1.0,
constant: 10)
constraints.append(constraintTop)
constraintBottom = NSLayoutConstraint(item: textView,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1.0,
constant: 10)
constraints.append(constraintBottom)
constraintLeft = NSLayoutConstraint(item: textView,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Leading,
multiplier: 1.0,
constant: 10)
constraints.append(constraintLeft)
constraintRight = NSLayoutConstraint(item: textView,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1.0,
constant: 10)
constraints.append(constraintRight)
self.view.addConstraints(constraints)
You can fix this in one of two ways:
Change the constant to -10 for your bottom and trailing constraints.
or
Switch the order of the item: and toItem: values in the bottom and trailing constraints. That is, make item: self.view and toItem: textView for the bottom and trailing constraints. This is how it is done if you set the constraints in the StoryBoard.

Adding NSLayoutConstraints to UISegmentedControl causes UISegmentedControl to disappear

I have a UISegmentedControl defined programmatically.
I am trying to add a layout constraint so that when my iPad rotates, the segmented control sizes correctly within the rotated view rather than spill off screen.
I apply the following constraint:
streamSegmentedControl.translatesAutoresizingMaskIntoConstraints = false
let segmentedControlWidth = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Width,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Width,
multiplier: 1.0,
constant: -10.0)
containerView.addConstraint(segmentedControlWidth)
My UIsegmentControl is defined as follows:
streamSegmentedControl = UISegmentedControl(items: ["Today's Events", "Past Events"])
streamSegmentedControl.frame = CGRectMake(-10,containerView.frame.size.height*0.3,containerView.frame.width+20,40)
streamSegmentedControl.selectedSegmentIndex = 0
streamScope = "today"
streamSegmentedControl.setTitleTextAttributes(segmentedControlFont as [NSObject : AnyObject], forState: .Normal)
streamSegmentedControl.backgroundColor = UIColor.colorFromClass("background")
streamSegmentedControl.tintColor = UIColor.colorFromClass("default")
streamSegmentedControl.addTarget(self, action: "changeStreamScope:", forControlEvents: UIControlEvents.ValueChanged)
containerView.addSubview(streamTableView)
containerView.addSubview(streamSegmentedControl)
I don't get an error, but at runtime, my segmented control disappears. Not sure what I am missing here as I've only done auto layout within storyboards in the past.
I only want to be able to adjust the width of the segmented control, so I assume I only need a single layout constraint.
Can anyone give me some direction? Thanks.
You need to add three constraints at least. Leading, top and trailing.
I am weak in swift but your constraints should look like.
let segmentedControlTop = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Top,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let segmentedControlLeading = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Leading,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
let segmentedControlTrailing = NSLayoutConstraint(item: streamSegmentedControl,
attribute: .Trailing,
relatedBy: .Equal,
toItem: self.containerView,
attribute: .Trailing,
multiplier: 1.0,
constant: 0.0)
containerView.addConstraint(segmentedControlTop)
containerView.addConstraint(segmentedControlLeading)
containerView.addConstraint(segmentedControlTrailing)
If you want to keep a 5 point offset from superview, try playing with constant values of leading and trailing using 5 points.

UIScrollView with dynamically created UIButtons not Scrolling

I am using Xcode 6.2 and Swift. I have set up with storyboard a UIScrollView which I fill with varying numbers of programmatically created buttons. Each button varies in height due to the data contained. All of this usually creates a list longer than a single screen thus requiring scroll ability. As I loop and create each button I also adjust the height of the button to meet the needs of the content. So, in short varying numbers of buttons of varying size. I am able to set the height for the scrollView by summing up each buttons height during creation. Suddenly I cannot scroll the buttons anymore. I have tried many of the suggestions made on this site for other related questions but none fix my problem.
some code:
// Add constraints depending on what number button it is
let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codeData, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: CGFloat(buttonHeight))
codeData.addConstraint(heightConstraint)
let leftMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codeData, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.scrollviewContentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 900)
let rightMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codeData, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.scrollviewContentView, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 900)
let topMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codeData, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.scrollviewContentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: CGFloat(sumOfButtonTops))
self.scrollviewContentView.addConstraints([leftMarginConstraint,rightMarginConstraint, topMarginConstraint])
let contentViewHeight:NSLayoutConstraint = NSLayoutConstraint(item: self.scrollviewContentView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.codeButtonArray[0], attribute: NSLayoutAttribute.Height, multiplier: 1, constant: CGFloat(sumOfButtonTops + 30))