programmatic constraints - cover entire superview using layout anchors - ios

Is it possible using layout anchors to cover an entire superview's screen?
Using NSLayoutConstraints, I can achieve this effect using the code below
dimmingView = UIView()
dimmingView.translatesAutoresizingMaskIntoConstraints = false
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
containerView?.addSubview(dimmingView)
NSLayoutConstraint(item: containerView!, attribute: .leadingMargin, relatedBy: .equal, toItem: dimmingView, attribute: .leadingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .trailingMargin, relatedBy: .equal, toItem: dimmingView, attribute: .trailingMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .topMargin, relatedBy: .equal, toItem: dimmingView, attribute: .topMargin, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: containerView!, attribute: .bottomMargin, relatedBy: .equal, toItem: dimmingView, attribute: .bottomMargin, multiplier: 1, constant: 0).isActive = true
I want to switch to layout anchors instead, following what's suggested in the docs. I tried doing this:
let margins = containerView?.layoutMarginsGuide
dimmingView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
dimmingView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
dimmingView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
dimmingView.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
or this
let margins = containerView?.layoutMarginsGuide
dimmingView.heightAnchor.constraint(equalTo: margins.heightAnchor).isActive = true
dimmingView.widthAnchor.constraint(equalTo: margins.widthAnchor).isActive = true
dimmingView.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true
dimmingView.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true
but both did not work. Instead of fully covering containerview, what I end up with are paddings at all 4 sides.

You are constraining to margins and the margins are the space you see. constrain to superview instead:.
dimmingView.heightAnchor.constraint(equalTo: dimmingView.superview!.heightAnchor).isActive = true
dimmingView.widthAnchor.constraint(equalTo: dimmingView.superview!.widthAnchor).isActive = true
dimmingView.centerXAnchor.constraint(equalTo: dimmingView.superview!.centerXAnchor).isActive = true
dimmingView.centerYAnchor.constraint(equalTo: dimmingView.superview!.centerYAnchor).isActive = true

You have to use the attributes .leading, .trailing, .topand .bottom instead of the corresponding .xxxMargin attributes. They will place the subview along the superviews bounds.

Related

How do I create a robust ScrollView with both horizontal and vertical paging using autoLayout?

Situation
So I'm trying to make a UIScrollView that is basically a menu navigation bar that a user can navigate by swiping between menu items, where there are pages vertically laid out, and sub-pages horizontally laid out. Mockup:
The way I'm doing this is by creating a UIScrollView whose frame is the size of one UILabel, and I have isPagingEnabled set to true. I then tried adding a UIStackView, with each row indicating a page, and the contents of each row being a sub-page. I set the scrollView.contentSize to be the size of the UIStackView. The problem is that all my label's frames are zeros all through and the UIScrollView doesn't work.
:/
I really wanted to avoid getting help as I felt like I could do this by myself but I've spent two days on this and I've lost all hope.
Code
Here is the code where I add the labels. It's called upon the scrollview's superview's init (because the UIScrollView is in a custom UIView I call crossNavigation View).
private func addScrollViewLabels() {
//Get Max Number of Items in a Single Row
var maxRowCount = -1
for item in items {
if (item.contents.count > maxRowCount) {maxRowCount = item.contents.count}
}
self.rowsStackView.axis = .vertical
self.rowsStackView.distribution = .fillEqually
self.rowsStackView.alignment = .fill
self.rowsStackView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.addSubview(rowsStackView)
for i in 0 ..< items.count {
let row = items[i].contents
let rowView = UIView()
self.rowsStackView.addArrangedSubview(rowView)
var rowLabels : [UILabel] = []
//First Label
rowLabels.append(UILabel())
rowView.addSubview(rowLabels[0])
NSLayoutConstraint(item: rowLabels[0], attribute: .leading, relatedBy: .equal, toItem: rowView, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: rowLabels[0], attribute: .top, relatedBy: .equal, toItem: rowView, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: rowLabels[0], attribute: .bottom, relatedBy: .equal, toItem: rowView, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: rowLabels[0], attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.55, constant: 0.0).isActive = true
//Middle Labels
for j in 1 ..< row.count {
rowLabels.append(UILabel())
rowView.addSubview(rowLabels[j])
//Stick it to it's left
NSLayoutConstraint(item: rowLabels[j], attribute: .leading, relatedBy: .equal, toItem: rowLabels[j-1], attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true
//Stick top to rowView
NSLayoutConstraint(item: rowLabels[j], attribute: .top, relatedBy: .equal, toItem: rowView, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
//Row Height is equal to rowView's Height
NSLayoutConstraint(item: rowLabels[j], attribute: .height, relatedBy: .equal, toItem: rowView, attribute: .height, multiplier: 1.0, constant: 0.0).isActive = true
//rowLabels[j].width = containerView.width * 0.55 (so other labels can peek around it)
NSLayoutConstraint(item: rowLabels[j], attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.55, constant: 0.0).isActive = true
}
//lastLabel.trailing = rowView.trailing
NSLayoutConstraint(item: rowLabels[row.count-1], attribute: .trailing, relatedBy: .equal, toItem: rowView, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true
}
//Constraints for stack view:
//rowsStackView.height = scrollView.height * items.count
NSLayoutConstraint(item: rowsStackView, attribute: .height, relatedBy: .equal, toItem: scrollView, attribute: .height, multiplier: CGFloat(self.items.count), constant: 0.0).isActive = true
//rowsStackView.height = scrollView.height * items.count
NSLayoutConstraint(item: rowsStackView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: rowsStackView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: rowsStackView, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true
self.scrollView.contentSize = rowsStackView.frame.size
}
Take a look at this demo project I made based off your mock up.
It sets up the framework for everything you want to do.
Examine the view hierarchy and you'll understand where to configure the layout to make it exactly how you want.
The last step is to tweak the paging so you get the snap behavior you desire. There are many ways to do this but it is a bit involved.
Good Luck!

How to set an element center of view programmatically in iOS Swift 3?

I have a view and I want to center it horizontally and vertically in its superview.
I tried this but it's not working:
let horConstraint = NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0)
view.addConstraints([horConstraint])
I would suggest trying to use Anchors which are more convenient and easy to understand. This code centered my view:
let someView = UIView()
someView.backgroundColor = .red
someView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(someView)
NSLayoutConstraint.activate([
someView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
someView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
someView.heightAnchor.constraint(equalToConstant: 50),
someView.widthAnchor.constraint(equalToConstant: 50)
])
Try this:
Note: Make sure that you are setting this property (before applying constraints) to false for webView
webView.translatesAutoresizingMaskIntoConstraints = false
For x axis
let horConstraint = NSLayoutConstraint(item: webView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX ,multiplier: 1.0, constant: 0.0)
For y axis
let verConstraint = NSLayoutConstraint(item: webView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY ,multiplier: 1.0, constant: 0.0)
view.addConstraints([horConstraint, verConstraint])

Swift: how to center elements horizontally in vertical stackview

I have stackview with four elements that need to be centered horizontally:
let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing = 5.0
stackView.addArrangedSubview(browseButton)
stackView.addArrangedSubview(orLabel)
stackView.addArrangedSubview(createButton)
stackView.addArrangedSubview(imageView)
let imageViewCenterXConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: stackView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
stackView.addConstraint(imageViewCenterXConstraint)
stackView.translatesAutoresizingMaskIntoConstraints = false
let stackViewCenterXConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let stackViewCenterYConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
wantMorePage?.backgroundColor = UIColor.gray
wantMorePage!.addSubview(stackView)
wantMorePage!.addConstraint(stackViewCenterXConstraint)
wantMorePage!.addConstraint(stackViewCenterYConstraint)
self.scrollView.addSubview(wantMorePage!)
I added constraints and set alignment to center, but elements are still not centered (screenshot). What should I do to center them?
Replace:
wantMorePage!.addConstraint(stackViewCenterXConstraint)
wantMorePage!.addConstraint(stackViewCenterYConstraint)
With:
stackViewCenterXConstraint.isActive = true
stackViewCenterYConstraint.isActive = true
https://developer.apple.com/documentation/uikit/uiview/1622523-addconstraint
Also you need to add the subView before you can add constraints to it
Move this above isActive calls:
self.scrollView.addSubview(wantMorePage!)
Like so:
wantMorePage!.addSubview(stackView)
self.scrollView.addSubview(wantMorePage!)
let imageViewCenterXConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: stackView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
imageViewCenterXConstraint.isActive = true
let stackViewCenterXConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let stackViewCenterYConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
stackViewCenterXConstraint.isActive = true
stackViewCenterYConstraint.isActive = true
Found what the issue was - the width of the view was incorrect, in my code wantMorePage was bigger than needed, I made it the same size as its superview and it fixed the issue.

NSLayoutConstraint - can't set subview frame to parent view bounds

I have a testView UIView and subview named testViewSub. The testView is constrained by using NSLayoutConstraint. And i set subView frame to testView.bounds. But it doesn't work. Here is the code
let testView = UIView()
testView.backgroundColor = UIColor.red
self.view.addSubview(testView)
testView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: testView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 30).isActive = true
NSLayoutConstraint(item: testView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: -30).isActive = true
NSLayoutConstraint(item: testView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 200).isActive = true
NSLayoutConstraint(item: testView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.15, constant: 0).isActive = true
let testViewSub = UIView()
testViewSub.backgroundColor = UIColor.green
testViewSub.frame = testView.bounds
self.testView.addSubview(testViewSub)
testViewSub.translatesAutoresizingMaskIntoConstraints = false
But if i set testView's frame using CGRect. It works.
Where is the layout happening? I've run into issues before where the constraints don't take effect until the view appears, so relying on frames to be the correct size in viewDidLoad or viewWillAppear causes problems.
In this case, adding testViewSub in viewDidAppear worked for me, though I'm not sure it's the way I would recommend. Using constraints to lay it out, just as with testView, will also work from viewDidLoad or viewWillAppear:
// layout constraints however you want - in this case they are such that green view's frame = red view's bounds
let testViewSub = UIView()
testViewSub.backgroundColor = UIColor.green
self.testView.addSubview(testViewSub)
NSLayoutConstraint(item: testViewSub, attribute: .leading, relatedBy: .equal, toItem: testView, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: testViewSub, attribute: .trailing, relatedBy: .equal, toItem: testView, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: testViewSub, attribute: .top, relatedBy: .equal, toItem: testView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: testViewSub, attribute: .height, relatedBy: .equal, toItem: testView, attribute: .height, multiplier: 1.0, constant: 0).isActive = true
testViewSub.translatesAutoresizingMaskIntoConstraints = false
This will also deal with rotation better than simply setting the frame.

Auto set height of container view based on subviews

I know this question has been asked numerous times, but I can't quite seem to get to the bottom of this problem.
Using Auto Layout, I would like to automatically set the height of my container UIView based on its subviews. I have looked at using sizeToFit and other various methods of summing up the height of my subviews, however from what I've read the height of my container height should be automatic when using Auto Layout because of the subviews "intrinsic" content size.
Below is a reduced case of what I'm experiencing. I would really appreciate any guidance!
Overview:
Create container UIView, pin to left and right sides of superview, no explicit height, align its centerY with its superview centerY
Create a 300 width by 100 height UIView, add it as a subview to container view, align its centerX with container view's centerX, pin to container view's top edge
Repeat step #2, except this time pin its top to #2's bottom edge
The expected height of the container view is 200, except its height is actually still 0 (therefor centerY alignment is off)
Code:
class ViewController: UIViewController {
let redView = RedView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(redView)
view.setNeedsUpdateConstraints()
}
}
class RedView: UIView {
let greenView = GreenView()
let blueView = BlueView()
init() {
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.red()
addSubview(greenView)
addSubview(blueView)
setNeedsUpdateConstraints()
}
override func updateConstraints() {
super.updateConstraints()
NSLayoutConstraint(item: greenView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: blueView, attribute: .top, relatedBy: .equal, toItem: greenView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: superview, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: superview, attribute: .right, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: superview, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200).isActive = true
}
}
class GreenView: UIView {
init() {
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.green()
}
override func updateConstraints() {
super.updateConstraints()
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300).isActive = true
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100).isActive = true
NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
}
}
class BlueView: UIView {
init() {
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.blue()
}
override func updateConstraints() {
super.updateConstraints()
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300).isActive = true
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100).isActive = true
NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
}
}
You need to pin blueView's bottom to redView's bottom, just add this line to redView's updateConstraints:
NSLayoutConstraint(item: blueView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).active = true

Resources