I'm working with a UIViewController and have two main displays of type UIViewController that I want to programmatically switch between. In order to do this I called addChild() two separate times upon instantiating the parent view controller.
Then later, when I want to switch between them I simply modify the isHidden property of each of them.
However, I believe this is causing some unintended behavior upon launch, where the UIViewController that is added first cannot be displayed without first displaying the UIViewController that's added second.
Doing research I couldn't find examples of people calling addChild() multiple times, and I was wondering if this is common practice or if there is a more common approach that might eliminate room for error. The documentation for addChild() says nothing about calling it multiple times. I'm quite new to Swift, but have experience with other programming languages, so I'm hoping to understand what I'm working with better.
There is no problem adding multiple child view controllers.
Here's how it could look (in viewDidLoad() of the "parent" view controller):
// instantiate 3 view controllers
let firstVC = FirstVC()
let secondVC = SecondVC()
let thirdVC = ThirdVC()
// for each view controller
[firstVC, secondVC, thirdVC].forEach { vc in
// add it as a child
self.addChild(vc)
// add its view
view.addSubview(vc.view)
// layout its view
vc.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// we'll constrain all 4 sides to the safe area
// with 20-points "padding" all around
vc.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
vc.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
vc.view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
vc.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20.0),
])
// start with all child controller views hidden
vc.view.isHidden = true
// finish the add child process
vc.didMove(toParent: self)
}
View controllers maintain an array of "children" - so we can then "show" the first child's view like this:
// show first child controller view
self.children.first?.view.isHidden = false
Here's a quick, runnable example...
We create 3 view controllers, add them as child controllers, add their views (and set up constraints). Then we'll add a UISegmentedControl to switch between the child controllers' views.
So, it will look like this:
class MultiChildViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let seg = UISegmentedControl(items: ["First", "Second", "Third"])
seg.addTarget(self, action: #selector(segChanged(_:)), for: .valueChanged)
seg.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(seg)
// respect safe area
let safeG = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
seg.topAnchor.constraint(equalTo: safeG.topAnchor, constant: 20.0),
seg.leadingAnchor.constraint(equalTo: safeG.leadingAnchor, constant: 20.0),
seg.trailingAnchor.constraint(equalTo: safeG.trailingAnchor, constant: -20.0),
])
// instantiate 3 view controllers
let firstVC = FirstVC()
let secondVC = SecondVC()
let thirdVC = ThirdVC()
// for each view controller
[firstVC, secondVC, thirdVC].forEach { vc in
// add it as a child
self.addChild(vc)
// add its view
view.addSubview(vc.view)
// layout its view
vc.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// constrain top to segmented control bottom plus 20-points
vc.view.topAnchor.constraint(equalTo: seg.bottomAnchor, constant: 20.0),
// we'll constrain leading/trailing/bottom to the safe area
// with 20-points "padding"
vc.view.leadingAnchor.constraint(equalTo: safeG.leadingAnchor, constant: 20.0),
vc.view.trailingAnchor.constraint(equalTo: safeG.trailingAnchor, constant: -20.0),
vc.view.bottomAnchor.constraint(equalTo: safeG.bottomAnchor, constant: -20.0),
])
// start with all child controller views hidden
vc.view.isHidden = true
// finish the add child process
vc.didMove(toParent: self)
}
// set the segmented control's selected segment to Zero
seg.selectedSegmentIndex = 0
// show first child controller view
self.children.first?.view.isHidden = false
}
#objc func segChanged(_ sender: UISegmentedControl) {
let idx = sender.selectedSegmentIndex
for (i, vc) in self.children.enumerated() {
vc.view.isHidden = i != idx
}
}
}
class FirstVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemRed
let v = UILabel()
v.textAlignment = .center
v.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
v.text = "First VC"
v.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(v)
NSLayoutConstraint.activate([
v.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0),
v.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0),
v.heightAnchor.constraint(equalToConstant: 100.0),
v.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
class SecondVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemGreen
let v = UILabel()
v.textAlignment = .center
v.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
v.text = "Second VC"
v.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(v)
NSLayoutConstraint.activate([
v.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0),
v.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0),
v.heightAnchor.constraint(equalToConstant: 100.0),
v.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
class ThirdVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBlue
let v = UILabel()
v.textAlignment = .center
v.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
v.text = "Third VC"
v.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(v)
NSLayoutConstraint.activate([
v.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0),
v.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0),
v.heightAnchor.constraint(equalToConstant: 100.0),
v.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
Related
Update:
Thanks everyone for the unique approaches. Appreciate your insights.
Background:
I have written some code below in Xcode Swift 5 that creates four equal sized rectangles that resize depending on the device size and orientation.
However, the desired result is a rectangle with different heights, where the top rectangles are variable heights depending on the device size and orientation, and the bottom rectangles are with a constant height of 200px.
Question:
What changes to my code do I need to make to achieve variable heights on top and fixed heights on bottom?
Code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frameTopLeft = UIView()
frameTopLeft.backgroundColor = .systemRed
view.addSubview(frameTopLeft)
frameTopLeft.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameTopLeft.topAnchor.constraint(equalTo: view.topAnchor),
frameTopLeft.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
frameTopLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameTopLeft.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
let frameTopRight = UIView()
frameTopRight.backgroundColor = .systemBlue
view.addSubview(frameTopRight)
frameTopRight.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameTopRight.topAnchor.constraint(equalTo: view.topAnchor),
frameTopRight.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
frameTopRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameTopRight.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
let frameBottomLeft = UIView()
frameBottomLeft.backgroundColor = .systemGreen
view.addSubview(frameBottomLeft)
frameBottomLeft.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameBottomLeft.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomLeft.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
frameBottomLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameBottomLeft.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
let frameBottomRight = UIView()
frameBottomRight.backgroundColor = .systemYellow
view.addSubview(frameBottomRight)
frameBottomRight.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameBottomRight.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomRight.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
frameBottomRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameBottomRight.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
}
}
Images:
Simulator output.
Desired output.
Use StackView for better code and understanding.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let topStack = UIStackView()
topStack.axis = .horizontal
topStack.distribution = .fillEqually
let frameTopLeft = UIView()
frameTopLeft.backgroundColor = .systemRed
topStack.addArrangedSubview(frameTopLeft)
let frameTopRight = UIView()
frameTopRight.backgroundColor = .systemBlue
topStack.addArrangedSubview(frameTopRight)
let bottomStack = UIStackView()
bottomStack.axis = .horizontal
bottomStack.distribution = .fillEqually
let frameBottomLeft = UIView()
frameBottomLeft.backgroundColor = .systemGreen
bottomStack.addArrangedSubview(frameBottomLeft)
let frameBottomRight = UIView()
frameBottomRight.backgroundColor = .systemYellow
bottomStack.addArrangedSubview(frameBottomRight)
frameBottomRight.translatesAutoresizingMaskIntoConstraints = false
frameBottomRight.heightAnchor.constraint(equalToConstant: 200).isActive = true
let mainStack = UIStackView()
mainStack.axis = .vertical
mainStack.addArrangedSubview(topStack)
mainStack.addArrangedSubview(bottomStack)
self.view.addSubview(mainStack)
mainStack.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
mainStack.topAnchor.constraint(equalTo: view.topAnchor),
mainStack.heightAnchor.constraint(equalTo: view.heightAnchor),
mainStack.leftAnchor.constraint(equalTo: view.leftAnchor),
mainStack.widthAnchor.constraint(equalTo: view.widthAnchor)
])
}
}
Or you can give relative constraints to each bottom view.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frameTopLeft = UIView()
frameTopLeft.backgroundColor = .systemRed
view.addSubview(frameTopLeft)
frameTopLeft.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameTopLeft.topAnchor.constraint(equalTo: view.topAnchor),
// frameTopLeft.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5), << Here
frameTopLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameTopLeft.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
let frameTopRight = UIView()
frameTopRight.backgroundColor = .systemBlue
view.addSubview(frameTopRight)
frameTopRight.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameTopRight.topAnchor.constraint(equalTo: view.topAnchor),
// frameTopRight.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5), << Here
frameTopRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameTopRight.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
let frameBottomLeft = UIView()
frameBottomLeft.backgroundColor = .systemGreen
view.addSubview(frameBottomLeft)
frameBottomLeft.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameBottomLeft.topAnchor.constraint(equalTo: frameTopLeft.bottomAnchor), // << Here
frameBottomLeft.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomLeft.heightAnchor.constraint(equalToConstant: 200), // << Here
frameBottomLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameBottomLeft.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
let frameBottomRight = UIView()
frameBottomRight.backgroundColor = .systemYellow
view.addSubview(frameBottomRight)
frameBottomRight.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameBottomRight.topAnchor.constraint(equalTo: frameTopRight.bottomAnchor), // << Here
frameBottomRight.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomRight.heightAnchor.constraint(equalToConstant: 200), // << Here
frameBottomRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameBottomRight.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5)
])
}
}
You want to give the Bottom views constant Height constraints of 200, and then constrain the Bottoms of the top views to the Tops of the Bottom views.
You may find it helpful to group related code together, and add comments as you go (to make it a little clearer what you believe the code should do).
So, try it like this:
override func viewDidLoad() {
super.viewDidLoad()
// create 4 views
let frameTopLeft = UIView()
let frameTopRight = UIView()
let frameBottomLeft = UIView()
let frameBottomRight = UIView()
// set background colors
frameTopLeft.backgroundColor = .systemRed
frameTopRight.backgroundColor = .systemBlue
frameBottomLeft.backgroundColor = .systemGreen
frameBottomRight.backgroundColor = .systemYellow
// set Autoresizing and add to view
[frameTopLeft, frameTopRight, frameBottomLeft, frameBottomRight].forEach { v in
v.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(v)
}
NSLayoutConstraint.activate([
// top-left view constrained Top / Left / 50% Width
frameTopLeft.topAnchor.constraint(equalTo: view.topAnchor),
frameTopLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameTopLeft.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
// top-right view constrained Top / Right / 50% Width
frameTopRight.topAnchor.constraint(equalTo: view.topAnchor),
frameTopRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameTopRight.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
// bottom-left view constrained Bottom / Left / 50% Width
frameBottomLeft.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameBottomLeft.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
// bottom-right view constrained Bottom / Right / 50% Width
frameBottomRight.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameBottomRight.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
// bottom views, constant Height of 200-pts
frameBottomLeft.heightAnchor.constraint(equalToConstant: 200.0),
frameBottomRight.heightAnchor.constraint(equalToConstant: 200.0),
// constrain bottoms of top views to tops of bottom views
frameTopLeft.bottomAnchor.constraint(equalTo: frameBottomLeft.topAnchor),
frameTopRight.bottomAnchor.constraint(equalTo: frameBottomRight.topAnchor),
])
}
I'd do it like this:
let frameTopLeft = UIView()
frameTopLeft.backgroundColor = .systemRed
view.addSubview(frameTopLeft)
frameTopLeft.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameTopLeft.topAnchor.constraint(equalTo: view.topAnchor),
frameTopLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
])
let frameTopRight = UIView()
frameTopRight.backgroundColor = .systemBlue
view.addSubview(frameTopRight)
frameTopRight.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameTopRight.topAnchor.constraint(equalTo: view.topAnchor),
frameTopRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameTopRight.leftAnchor.constraint(equalTo: frameTopLeft.rightAnchor),
frameTopRight.widthAnchor.constraint(equalTo: frameTopLeft.widthAnchor)
])
let frameBottomLeft = UIView()
frameBottomLeft.backgroundColor = .systemGreen
view.addSubview(frameBottomLeft)
frameBottomLeft.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameBottomLeft.topAnchor.constraint(equalTo: frameTopLeft.bottomAnchor),
frameBottomLeft.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomLeft.leftAnchor.constraint(equalTo: view.leftAnchor),
frameBottomLeft.heightAnchor.constraint(equalToConstant: 200),
])
let frameBottomRight = UIView()
frameBottomRight.backgroundColor = .systemYellow
view.addSubview(frameBottomRight)
frameBottomRight.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
frameBottomRight.topAnchor.constraint(equalTo: frameTopRight.bottomAnchor),
frameBottomRight.bottomAnchor.constraint(equalTo: view.bottomAnchor),
frameBottomRight.rightAnchor.constraint(equalTo: view.rightAnchor),
frameBottomRight.leftAnchor.constraint(equalTo: frameBottomLeft.rightAnchor),
frameBottomRight.heightAnchor.constraint(equalTo: frameBottomLeft.heightAnchor),
frameBottomRight.widthAnchor.constraint(equalTo: frameBottomLeft.widthAnchor),
])
The main diff from others is getting rid of constants as much as possible.
Your bottom views should be 200? Add single 200 constraint, and make second view height be equal to the first one.
Instead of making width equal 50% of parent, you can make left width be equal right one
It makes you code easier to maintain, decreasing places to edit.
I have some problems with scrollview. I added a ScrollView to my ViewController with simple UIViews. But the ScrollView does not scroll and it does not show all my subviews.
I followed this example IOS swift scrollview programmatically but somehow my code does not work. Here is my example
import UIKit
class StatisticsViewController: UIViewController{
let scrollView: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = UIColor.lightGray.adjust(by: 28)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let topstatsView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
return view
}()
let resultsView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .systemPink
return view
}()
let blue: UIView = {
let view = UIView()
view.backgroundColor = .blue
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let yellow: UIView = {
let view = UIView()
view.backgroundColor = .yellow
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(scrollView)
// constraints of scroll view
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.addSubview(topstatsView)
scrollView.addSubview(resultsView)
scrollView.addSubview(blue)
scrollView.addSubview(yellow)
NSLayoutConstraint.activate([
topstatsView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 40),
topstatsView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 30),
topstatsView.heightAnchor.constraint(equalToConstant: 250),
topstatsView.rightAnchor.constraint(equalTo: scrollView.rightAnchor)
])
NSLayoutConstraint.activate([
resultsView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 330),
resultsView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 30),
resultsView.heightAnchor.constraint(equalToConstant: 400),
resultsView.widthAnchor.constraint(equalToConstant: 450)
])
NSLayoutConstraint.activate([
blue.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 330),
blue.leftAnchor.constraint(equalTo: resultsView.rightAnchor, constant: 20),
blue.heightAnchor.constraint(equalToConstant: 400),
blue.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -30)
])
NSLayoutConstraint.activate([
yellow.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 800),
yellow.leadingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 20),
yellow.heightAnchor.constraint(equalToConstant: 400),
yellow.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -30)
])
}
Here is a screenshot of my example.
As you can see the red view (topstatsView) does not confirm the right anchor and you cannot see the yellow and blue ones. And it is not scrollable. I am not able to see my mistakes. Thanks in advance!
Here you define wrong constraint.
1) Always add constraints related to each views top, bottom, leading and trailing, instead of define top constraint of all views to a scrollview.
2) Its not a good practise to add both leading and trailing anchor when you already define a width anchor.
3) Add bottom constraint related to a scrollview bottom to make it scrollable.
4) Add leading and trailing constraint related to outerView instead of adding it related to a scrollview.
Here is the updated code:-
class StatisticsViewController: UIViewController{
let scrollView: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = UIColor.lightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let topstatsView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
return view
}()
let resultsView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .systemPink
return view
}()
let blue: UIView = {
let view = UIView()
view.backgroundColor = .blue
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let yellow: UIView = {
let view = UIView()
view.backgroundColor = .yellow
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(scrollView)
// constraints of scroll view
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.addSubview(topstatsView)
scrollView.addSubview(resultsView)
scrollView.addSubview(blue)
scrollView.addSubview(yellow)
NSLayoutConstraint.activate([
topstatsView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 40),
topstatsView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 30),
topstatsView.heightAnchor.constraint(equalToConstant: 250),
topstatsView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -30)
])
NSLayoutConstraint.activate([
resultsView.topAnchor.constraint(equalTo: topstatsView.bottomAnchor, constant: 30),
resultsView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 30),
resultsView.heightAnchor.constraint(equalToConstant: 400),
resultsView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -30)
])
NSLayoutConstraint.activate([
blue.topAnchor.constraint(equalTo: resultsView.bottomAnchor, constant: 30),
blue.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20),
blue.heightAnchor.constraint(equalToConstant: 400),
blue.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -30)
])
NSLayoutConstraint.activate([
yellow.topAnchor.constraint(equalTo: blue.bottomAnchor, constant: 30),
yellow.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20),
yellow.heightAnchor.constraint(equalToConstant: 400),
yellow.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -30),
yellow.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor, constant: -20)
])
}
}
I want to animate hide show when one of my view is hidden. so I'm using content hugging priority to animate that, but it failed it has a gap between view. here I show you the ui and my code
This is 3 uiview code like the picture above
scrollView.addSubview(chooseScheduleDropDown)
chooseScheduleDropDown.translatesAutoresizingMaskIntoConstraints = false
chooseScheduleDropDown.setContentCompressionResistancePriority(.required, for: .vertical)
NSLayoutConstraint.activate([
chooseScheduleDropDown.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
chooseScheduleDropDown.topAnchor.constraint(equalTo: scrollView.topAnchor),
chooseScheduleDropDown.widthAnchor.constraint(equalToConstant: 285),
chooseScheduleDropDown.heightAnchor.constraint(equalToConstant: 60)
])
scrollView.addSubview(entryView)
entryView.isHidden = true
entryView.setContentHuggingPriority(.defaultLow, for: .vertical)
entryView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
entryView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
entryView.topAnchor.constraint(equalTo: chooseScheduleDropDown.bottomAnchor, constant: topPadding),
entryView.widthAnchor.constraint(equalToConstant: 285),
entryView.heightAnchor.constraint(equalToConstant: 60)
])
scrollView.addSubview(chooseDateView)
chooseDateView.setContentHuggingPriority(.defaultLow, for: .vertical)
chooseDateView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
chooseDateView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
chooseDateView.topAnchor.constraint(equalTo: entryView.bottomAnchor, constant: topPadding),
chooseDateView.widthAnchor.constraint(equalToConstant: 285),
chooseDateView.heightAnchor.constraint(equalToConstant: 60)
])
After exchanging comments, you have a number of different tasks to work on.
But, to give you an example of one approach to showing / hiding the "middle" view and having the bottom view move up / down, here is something to try. It will look like this:
Tapping the top (red) view will hide the middle (green) view and slide the bottom (blue) view up. Tapping the top (red) view again will slide the bottom (blue) view down and show the middle (green) view.
This is done by creating two top constraints for the Bottom view. One relative to the bottom of the Top view, and the other relative to the bottom of the Middle view, with different .priority values.
The example code is fairly straight-forward, and the comments should make things clear. All done via code - no #IBOutlet or #IBAction connections - so just create a new view controller and assign its custom class to AnimTestViewController:
class DropDownView: UIView {
}
class AnimTestViewController: UIViewController {
let scrollView: UIScrollView = {
let v = UIScrollView()
return v
}()
let chooseScheduleDropDown: DropDownView = {
let v = DropDownView()
return v
}()
let entryView: DropDownView = {
let v = DropDownView()
return v
}()
let chooseDateView: DropDownView = {
let v = DropDownView()
return v
}()
var visibleConstraint: NSLayoutConstraint = NSLayoutConstraint()
var hiddenConstraint: NSLayoutConstraint = NSLayoutConstraint()
override func viewDidLoad() {
super.viewDidLoad()
[chooseScheduleDropDown, entryView, chooseDateView].forEach {
v in
v.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(v)
}
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
let g = view.safeAreaLayoutGuide
let topPadding: CGFloat = 20.0
// chooseDateView top anchor when entryView is visible
visibleConstraint = chooseDateView.topAnchor.constraint(equalTo: entryView.bottomAnchor, constant: topPadding)
// chooseDateView top anchor when entryView is hidden
hiddenConstraint = chooseDateView.topAnchor.constraint(equalTo: chooseScheduleDropDown.bottomAnchor, constant: topPadding)
// we will start with entryView visible
visibleConstraint.priority = .defaultHigh
hiddenConstraint.priority = .defaultLow
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),
scrollView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -40.0),
scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
chooseScheduleDropDown.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
chooseScheduleDropDown.topAnchor.constraint(equalTo: scrollView.topAnchor),
chooseScheduleDropDown.widthAnchor.constraint(equalToConstant: 285),
chooseScheduleDropDown.heightAnchor.constraint(equalToConstant: 60),
entryView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
entryView.topAnchor.constraint(equalTo: chooseScheduleDropDown.bottomAnchor, constant: topPadding),
entryView.widthAnchor.constraint(equalToConstant: 285),
entryView.heightAnchor.constraint(equalToConstant: 60),
chooseDateView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
//chooseDateView.topAnchor.constraint(equalTo: entryView.bottomAnchor, constant: topPadding),
visibleConstraint,
hiddenConstraint,
chooseDateView.widthAnchor.constraint(equalToConstant: 285),
chooseDateView.heightAnchor.constraint(equalToConstant: 60),
])
//entryView.isHidden = true
chooseScheduleDropDown.backgroundColor = .red
entryView.backgroundColor = .green
chooseDateView.backgroundColor = .blue
let tap = UITapGestureRecognizer(target: self, action: #selector(toggleEntryView(_:)))
chooseScheduleDropDown.addGestureRecognizer(tap)
}
#objc func toggleEntryView(_ sender: UITapGestureRecognizer) -> Void {
print("tapped")
// if entryView IS hidden we want to
// un-hide entryView
// animate alpha to 1.0
// animate chooseDateView down
// if entryView is NOT hidden we want to
// animate alpha to 0.0
// animate chooseDateView up
// hide entryView when animation is finished
let animSpeed = 0.5
if entryView.isHidden {
entryView.isHidden = false
hiddenConstraint.priority = .defaultLow
visibleConstraint.priority = .defaultHigh
UIView.animate(withDuration: animSpeed, animations: {
self.entryView.alpha = 1.0
self.view.layoutIfNeeded()
}, completion: { _ in
})
} else {
visibleConstraint.priority = .defaultLow
hiddenConstraint.priority = .defaultHigh
UIView.animate(withDuration: animSpeed, animations: {
self.entryView.alpha = 0.0
self.view.layoutIfNeeded()
}, completion: { _ in
self.entryView.isHidden = true
})
}
}
}
Do
// declare an instance property
var hCon:NSLayoutConstraint!
// get only the height constraint out of the activate block
hCon = entryView.heightAnchor.constraint(equalToConstant: 60)
hCon.isActive = true
and play with
hCon.constant = 300 / 0
view.layoutIfNeeded()
I’m trying to change some layouts I have to a number-less layout.
This is what I have for a segmented bar that should be inside a container view with something like this | - margin - segmented - margin -|
segmentedControl.leadingAnchor.constraint(equalToSystemSpacingAfter: margins.leadingAnchor, multiplier: 1),
segmentedControl.trailingAnchor.constraint(equalToSystemSpacingAfter: margins.trailingAnchor, multiplier: 1),
I know that the second line doesn’t make any sense, but I don’t see any equalToSystemSpacingBEFORE just after, and I’m not sure how to do it without having to rely only on layout propagation.
Basically, the leadingAchor works fine with this code, but the trailingAnchor (as the method name implies) adds the margin AFTER the trailing anchor, which is not what I want.
any ideas?
You can constrain the trailingAnchor of your "container" view relative to the trailingAnchor of your segmented control.
Here's a quick example which I believe gives you the layout you want:
class SysSpacingViewController: UIViewController {
let seg: UISegmentedControl = {
let v = UISegmentedControl(items: ["A", "B", "C"])
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let cView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .white
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemYellow
cView.addSubview(seg)
view.addSubview(cView)
let g = view.safeAreaLayoutGuide
let m = cView.layoutMarginsGuide
NSLayoutConstraint.activate([
cView.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),
cView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
cView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
cView.heightAnchor.constraint(equalToConstant: 70.0),
seg.leadingAnchor.constraint(equalToSystemSpacingAfter: m.leadingAnchor, multiplier: 1.0),
m.trailingAnchor.constraint(equalToSystemSpacingAfter: seg.trailingAnchor, multiplier: 1.0),
seg.centerYAnchor.constraint(equalTo: cView.centerYAnchor),
])
}
}
Result:
I think you can use this:
segmentedControl.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 8).isActive = true
segmentedControl.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -8).isActive = true
Please change the name of containerView and constants accordingly.
Some of the applications add extra padding on left and right to the UIScrollView instances when the device width is too large.
What's important, content of the UIScrollView is not restricted to fixed width, because user can scroll outside of the content. It looks like it would have contentInset set, which dynamically changes based on superview width. How can I achieve it?
Note
Screen from above is not implemented as a scrolling view, I just wanted to visualize the concept.
If it is an option at all, you can adjust left and right (trailing, leading) autolayout constraints.
The following code creates horizontally scrollable scrollView with two containers in it. The first container contains a subview (red rectangle) with some margins.
Scroll View with container.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
private let scrollView = UIScrollView()
private let contentView = UIView()
override func loadView() {
let view = UIView()
self.view = view
self.view.backgroundColor = UIColor.white
scrollView.isPagingEnabled = true
scrollView.isScrollEnabled = true
scrollView.isUserInteractionEnabled = true
scrollView.bounces = true
self.view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: self.view.topAnchor),
scrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
scrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor)
])
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.backgroundColor = UIColor(white: 0.9, alpha: 0.9)
scrollView.addSubview(contentView)
let widthAnchor = contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
let heightAnchor = contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
widthAnchor.priority = .defaultLow
heightAnchor.priority = .defaultLow
NSLayoutConstraint.activate([
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
contentView.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
widthAnchor,
heightAnchor
])
contentView.layer.borderWidth = 1
contentView.layer.borderColor = UIColor.red.cgColor
let containerView1 = UIView()
containerView1.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(containerView1)
containerView1.backgroundColor = UIColor(white: 0.4, alpha: 1)
NSLayoutConstraint.activate([
containerView1.topAnchor.constraint(equalTo: contentView.topAnchor),
containerView1.leftAnchor.constraint(equalTo: contentView.leftAnchor),
containerView1.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
containerView1.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
let container1Content = container1ContentView()
containerView1.addSubview(container1Content)
NSLayoutConstraint.activate([
container1Content.topAnchor.constraint(equalTo: containerView1.topAnchor, constant: 44),
container1Content.leftAnchor.constraint(equalTo: containerView1.leftAnchor, constant: 44),
container1Content.rightAnchor.constraint(equalTo: containerView1.rightAnchor, constant: -44),
container1Content.bottomAnchor.constraint(equalTo: containerView1.bottomAnchor, constant: -44)
])
let containerView2 = UIView()
containerView2.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(containerView2)
containerView2.backgroundColor = UIColor(white: 0.9, alpha: 1)
NSLayoutConstraint.activate([
containerView2.topAnchor.constraint(equalTo: contentView.topAnchor),
containerView2.leftAnchor.constraint(equalTo: containerView1.rightAnchor),
containerView2.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
containerView2.rightAnchor.constraint(equalTo: contentView.rightAnchor),
containerView2.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
}
private func container1ContentView() -> UIView {
let content = UIView()
content.translatesAutoresizingMaskIntoConstraints = false
content.backgroundColor = UIColor.red
return content
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()