Auto-Layout fit to parent via code in Swift - swift

I have a view i'm creating via code and adding to another view as subview.
The new superview can change it's frame over time and I want the newly created subview to change it's frame accordingly.
How can I do that using Auto-Layout via code in Swift?

Here is an example:
let view = UIView() // existing view
let subview = UIView()
subview.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(subview)
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: subview, attribute: .Bottom, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: subview, attribute: .Trailing, multiplier: 1.0, constant: 0.0))

iOS 13, swift 5
First, you add this code
subview.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(subview)
Then, there are two ways of doing this in newer versions of iOS.
With NSLayoutConstraint class
NSLayoutConstraint(item: subview, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0).isActive = true
With NSLayoutAnchor class (less verbose)
subview.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
subview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
subview.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
subview.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
Either way, on iOS 8 and later Apple recommends using isActive() instead of adding constraints directly to a view.
Additionally, I believe the purpose of the NSLayoutAnchor method is to be more concise and readable compared to NSLayoutConstraint.

As #rjobidon mentioned you should use following code (Swift3)
let view = UIView() // existing view
let subview = UIView()
subview.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(subview)
NSLayoutConstraint(item: subview, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: subview, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: subview, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true

You can also activate the constraints like that :
let view = UIView() // existing view
let subview = UIView()
subview.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(subview)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: subview.leadingAnchor),
view.trailingAnchor.constraint(equalTo: subview.trailingAnchor),
view.topAnchor.constraint(equalTo: subview.topAnchor),
view.bottomAnchor.constraint(equalTo: subview.bottomAnchor)
])

Related

A layout issue (NSLayoutConstraint) in an iOS app

In an iOS app I have an autolayout issue.
The 2 following screenshots show the problem.
The switch (UISwitch object) on the right is displaced horizontally, when it should be fixed. Can anyone see what is happening?
It is true that the string on the left is changing length, but I think (according to the way I have set the constraints up) the font should be resized or the string split in 2 lines; but not the switch displaced.
Here is the relevant swift code:
import UIKit
class My_ViewController: UIViewController {
let xPanel = UILabel(), yPanel = UILabel(),
khToggle = UISwitch(), khLabel = UILabel()
....
override func viewDidLoad() {
super.viewDidLoad()
layOutUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
.....
toggleKeepHide(khToggle)
}
func layOutUI() {
for component in [xPanel,yPanel,khLabel,khToggle] {
component.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(component)
}
...........
khLabel.numberOfLines = 0
khLabel.adjustsFontSizeToFitWidth = true
khToggle.addTarget(self,
action: #selector(toggleKeepHide(_:)),
for: .valueChanged)
view.addConstraints([
.........
NSLayoutConstraint(item: khToggle, attribute: .right, relatedBy: .equal,
toItem: view, attribute: .right, multiplier: 1.0, constant: -30.0),
NSLayoutConstraint(item: khToggle, attribute: .top, relatedBy: .equal,
toItem: yPanel, attribute: .bottom, multiplier: 1.0,
constant: 50.0),
NSLayoutConstraint(item: khLabel, attribute: .right, relatedBy: .equal,
toItem: khToggle, attribute: .left, multiplier: 1.0, constant: -23.0),
NSLayoutConstraint(item: khLabel, attribute: .centerY, relatedBy: .equal,
toItem: khToggle, attribute: .centerY, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: khLabel, attribute: .left, relatedBy: .equal,
toItem: view, attribute: .left, multiplier: 1.0, constant: 30.0)])
}
#objc func toggleKeepHide(_ sender: UISwitch) {
if sender.isOn {khLabel.text = "Hide this object from the wyxoug list."}
else {khLabel.text = "Keep this object in the wyxoug list."}
}
}
You haven't provided sufficient information to reproduce the problem. Here's a reduction of your code, in my view controller's viewDidLoad (I eliminated everything but the label and the switch, fixed your left and right (you should never use those), and changed the alignment between the two views to top instead of center):
khToggle = UISwitch()
khToggle.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(khToggle)
khLabel = UILabel()
khLabel.text = String(repeating: "word ", count: 40)
khLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(khLabel)
// Do any additional setup after loading the view.
khLabel.numberOfLines = 0
view.addConstraints([
NSLayoutConstraint(item: khToggle!, attribute: .trailing, relatedBy: .equal,
toItem: view, attribute: .trailing, multiplier: 1.0, constant: -30.0),
NSLayoutConstraint(item: khToggle!, attribute: .top, relatedBy: .equal,
toItem: view, attribute: .top, multiplier: 1.0,
constant: 50.0),
NSLayoutConstraint(item: khLabel!, attribute: .trailing, relatedBy: .equal,
toItem: khToggle, attribute: .leading, multiplier: 1.0, constant: -23.0),
NSLayoutConstraint(item: khLabel!, attribute: .top, relatedBy: .equal,
toItem: khToggle, attribute: .top, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: khLabel!, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1.0, constant: 30.0)])
The result displays fine; there are no constraint conflicts or ambiguities, and it looks as one would expect:
The horizontal constraints for the label and the toggle are competing against each other.
(If you step in to Xcode's visual debugger, you'll find that there is a warning: the UISwitch instance has an ambiguous width and horizontal position.)
Solution
You have provided absolute values to AutoLayout, and it cannot resolve the requirements. To fix this, introduce some flexibility in to the requirements by setting the compression resistance of the label to a lower value:
khLabel.setCompressionResistance(.defaultLow, for: .horizontal)

Formatting UICollectionViewCell inner items with constraints

I have a UICollectionViewCell and I want to be able to format the items inside of it more freely. That means - I want to be able to set constraints relative to the cell itself.
This is my cell:
And this is my code:
//image View Constraints
let productImageTopConstraint = NSLayoutConstraint(item: ProductImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 1) // constant was 10
let productImageBottomConstraint = NSLayoutConstraint(item: ProductImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -30)
let productImageLeadingConstraint = NSLayoutConstraint(item: ProductImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
let productImageTrailingConstraint = NSLayoutConstraint(item: ProductImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -10)
//product name field constraints
let productNameTopConstraint = NSLayoutConstraint(item: ProductName, attribute: .top, relatedBy: .equal, toItem: ProductImageView, attribute: .bottom, multiplier: 1, constant: 10)
let productNameBottomConstraint = NSLayoutConstraint(item: ProductName, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
let productNameLeadingConstraint = NSLayoutConstraint(item: ProductName, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
let productNameTrailingConstraint = NSLayoutConstraint(item: ProductName, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
What I want:
The ImageView to be closer to the cell's top edge
The product name label to be in the center
To be able to add another label between the product name label and the cell's bottom edge
How do I do that ? How do I take into account the cell's edges ?
You can use Layout Anchors to achieve this.
first get the margins of your UICollectionViewCell contentView like below
let margins = self.contentView.layoutMarginsGuide
1. The ImageView to be closer to the cell's top edge
Add following constraints relative to cell's content view margins like below
//Add top, left, right constraint relative to cell content view like below
yourImageView.topAnchor.constraint(equalTo: margins.topAnchor,constant:5).isActive = true
yourImageView.leftAnchor.constraint(equalTo: margins.leftAnchor,constant:5).isActive = true
yourImageView.rightAnchor.constraint(equalTo: margins.rightAnchor,constant:5).isActive = true
2. The product name label to be in the center
//To center align
yourLabel.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true
//Now set your label top anchor to display it below your image view
yourLabel.topAnchor.constraint(equalTo: yourImageView.bottomAnchor,constant:5).isActive = true
3. To be able to add another label between the product name label and the cell's bottom edge
anotherLabel.topAnchor.constraint(equalTo: yourLabel.bottomAnchor,constant:5).isActive = true
anotherLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
//To center align
anotherLabel.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true
UPDATE
Make sure you have added your control as subview and set translatesAutoresizingMaskIntoConstraints = false
The order in which you should add constraint programmatically is as follows
Initialise your controls like let yourLabel = UILabel()
Set yourLabel.translatesAutoresizingMaskIntoConstraints = false
Add your label as subview self.addSubView(yourLabel)
Add constraints to your label
1
let productImageTopConstraint = NSLayoutConstraint(item: ProductImageView,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 1) <- make it 0 so it will be pinned to top edge
2 Set ProductName.textAlignment = .center
3 a) Remove productNameBottomConstraint so ProductName's height will be calculated from text and font automatically
b) Add another label with layout
let productName2TopConstraint = NSLayoutConstraint(item: ProductName2, attribute: .top, relatedBy: .equal, toItem: ProductName, attribute: .bottom, multiplier: 1, constant: 10)
let productName2BottomConstraint = NSLayoutConstraint(item: ProductName2, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
let productName2LeadingConstraint = NSLayoutConstraint(item: ProductName2, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 10)
let productName2TrailingConstraint = NSLayoutConstraint(item: ProductName2, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)

UIScrollView with NSLayoutConstraint

UIScrollView is not scrolling the subviews but it does show a scroll-bar.
Here is what I am trying to do
class SetupViewController: UIViewController {
let scrollView = UIScrollView()
let pageLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.setupViews()
self.setupConstraints()
self.setText()
}
func setupViews() {
self.scrollView.backgroundColor = .red
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
// Page Label
self.pageLabel.font = UIFontLocalized(englishFontSize: 22, arabicFontSize: 22)
self.pageLabel.textAlignment = .center
self.pageLabel.translatesAutoresizingMaskIntoConstraints = false
}
func setupConstraints() {
// Add To Sub Views
self.view.addSubview(self.pageLabel)
self.view.addSubview(self.scrollView)
// Page Label
NSLayoutConstraint(item: self.pageLabel, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 30.0).isActive = true
NSLayoutConstraint(item: self.pageLabel, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 20.0).isActive = true
NSLayoutConstraint(item: self.pageLabel, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: -40.0).isActive = true
NSLayoutConstraint(item: self.pageLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 36.0).isActive = true
// Scroll View
NSLayoutConstraint(item: self.scrollView, attribute: .top, relatedBy: .equal, toItem: self.line1, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: self.scrollView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: self.scrollView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: self.scrollView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: -100.0).isActive = true
self.scrollView.contentSize.height = 2000
// NSLayoutConstraint for rest of elements are removed in this example code.
}
}
I can confirm UIScrollView is added in the view because I checked by giving background red color to scrollview and it does show the background red color in correct position. My issue is the subviews does not move only the scroll bar is moving.
What could be the possible issue here?
Note: NSLayoutConstraint exist for all UIKit elements, I have not added it in the code.
I got this issue sorted our. As pointed out in the comment, the issue was related to superview in constraint which was set to self.view changing it to self.scrollView solved the issue.

Swift constraint makes wrong element width smaller

so i have this UIStackView on the left of my view, I've done this using trailing space, and i have label, i want it to be on the left of my stack view, when i set constraints for label, instead of tightening label it makes stack view smaller, how do i solve this problem? i couldn't find any answers anywhere, i don't want to set the width constraint to the stack view because it might change, i just want to prioritize stack views width over label width
constraints:
NSLayoutConstraint(item: self.mainView, attribute: .Bottom, relatedBy: .Equal, toItem: stackView, attribute: .Bottom, multiplier: 1.0, constant: 10)
NSLayoutConstraint(item: self.mainView, attribute: .Trailing, relatedBy: .Equal, toItem: stackView, attribute: .Trailing, multiplier: 1.0, constant: 10)
NSLayoutConstraint(item: mainView, attribute: .Bottom, relatedBy: .Equal, toItem: Label, attribute: .Bottom, multiplier: 1.0, constant: 10)
NSLayoutConstraint(item: Label, attribute: .Leading, relatedBy: .Equal, toItem: mainView, attribute: .Leading, multiplier: 1.0, constant: 20)
NSLayoutConstraint(item: Stack, attribute: .Leading, relatedBy: .Equal, toItem: Label, attribute: .Trailing, multiplier: 1.0, constant: 10)
I've managed to do it by making distribution of stack view .FillEqually

After adding an NSLayoutConstraint, view disappears

When I add an NSLayoutConstraint to a view, it results in the view disappearing.
I am using the following code:
let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100))
test.backgroundColor = UIColor.blackColor()
self.view.addSubview(test)
test.translatesAutoresizingMaskIntoConstraints = false
let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: test.superview, attribute: .CenterX, multiplier: 0.5, constant: 0)
topCKCtr.active = true
let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: test.superview, attribute: .CenterY, multiplier: 0.5, constant: 0)
topCKCtr1.active = true
self.view.layoutIfNeeded()
self.view.setNeedsDisplay()
When I debug view hierarchy, i see that the view exists, even though it is not visible. See the below screenshot for details - only the constraint is visible, not the view:
There are so many things that needs to be discussed here.
When you use the following
test.translatesAutoresizingMaskIntoConstraints = false
Then it will totally rely on constraints to position and size a view.So you need to set height and width constraints of the view.
let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100)
let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100)
Finally This will be the code which you are looking for
let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100))
test.backgroundColor = UIColor.blackColor()
self.view.addSubview(test)
test.translatesAutoresizingMaskIntoConstraints = false
let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 0.5, constant: 0)
topCKCtr.active = true
let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 0.5, constant: 0)
topCKCtr1.active = true
let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100)
topCKCtr2.active = true
let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100)
topCKCtr3.active = true