How do I align ImageView to the bottom of ScrollView programmatically? - ios

I am trying to align a background image to the bottom of a scroll view that fits the screen, programmatically using Autolayout. Ideally, I want the image to be always aligned at the bottom of the scroll view. When the content of the scroll view goes beyond the screen height or when scroll view content size is less than screen height with scroll view fitting the whole screen.
MyView
class MyView: UIView {
let myScrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.bounces = false
return scrollView
}()
let contentView: UIView = {
let view = UIView()
view.backgroundColor = .red
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let myLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello world"
label.font = UIFont.systemFont(ofSize: 24)
return label
}()
let myImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = #imageLiteral(resourceName: "Mask Group 3")
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
backgroundColor = .white
addSubview(myScrollView)
myScrollView.addSubview(contentView)
contentView.addSubview(myLabel)
contentView.addSubview(myImageView)
}
private func setupConstraints() {
myScrollView.topAnchor.constraint(equalTo: topAnchor).isActive = true
myScrollView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
myScrollView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
myScrollView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: myScrollView.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: myScrollView.bottomAnchor).isActive = true
contentView.leftAnchor.constraint(equalTo: myScrollView.leftAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: myScrollView.rightAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
// If I am setting this and when the content size go beyond the screen, it does not scroll
// If I don't set this, there is no content size and image view will not position correctly
// contentView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
myLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 200).isActive = true
myLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
myImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
myImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
myImageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
}
}
MyViewController
import UIKit
class MyViewController: UIViewController {
override func loadView() {
view = MyView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Illustration

I have found the solution.
A contentView is needed.
Set the contentView's top, left, bottom, right constraint equal to scrollView edges.
Set the contentView's width equal to view's width anchor
Set the contentView's height greaterThanOrEqualTo view's height anchor
Set the imageView's bottom equal to the bottom anchor of contentView.
For the imageView's top, set the constraint to an element with greaterThanOrEqualTo, to give it a constant gap and avoid overlapping of elements in smaller screens.

It is seems ok:
private func setupConstraints() {
myScrollView.topAnchor.constraint(equalTo: topAnchor).isActive = true
myScrollView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
myScrollView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
myScrollView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: myScrollView.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: myScrollView.bottomAnchor).isActive = true
contentView.leftAnchor.constraint(equalTo: myScrollView.leftAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: myScrollView.rightAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
// If I am setting this and when the content size go beyond the screen, it does not scroll
// If I don't set this, there is no content size and image view will not position correctly
contentView.heightAnchor.constraint(equalToConstant: 1400).isActive = true
myLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 200).isActive = true
myLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
myImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
myImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
myImageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
myImageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
If think you just forgot to specify image height:
myImageView.heightAnchor.constraint(equalToConstant: 200).isActive = true

Related

Self-sizing custom UIView

I'm trying to compute the height of my custom UIView that's based on the contents of my UIStackView:
class CustomView: UIView {
let nameLabel = UILabel()
let descriptionLabel = UILabel()
let stackView = UIStackView()
init() {
super.init(frame: .zero)
nameLabel.numberOfLines = 0
descriptionLabel.numberOfLines = 0
stackView.addArrangedSubviews([nameLabel, descriptionLabel])
stackView.axis = .vertical
addSubview(stackView)
// constrain stack view to four sides
widthAnchor.constrain(to: 100) // hold width
}
func updateText(name: String, description: String) {
nameLabel.text = name
descriptionLabel.text = description
// resize custom view to fit text in nameLabel / descriptionLabel
}
}
The contents of nameLabel and descriptionLabel are populated at a later time. I'd like to resize the custom view based on the height of the labels. How can I achieve this?
add constraint to stackView and set translatesAutoresizingMaskIntoConstraints property false.
class CustomView: UIView {
let nameLabel = UILabel()
let descriptionLabel = UILabel()
let stackView = UIStackView()
init() {
super.init(frame: .zero)
nameLabel.numberOfLines = 0
descriptionLabel.numberOfLines = 0
stackView.addArrangedSubview(nameLabel)
stackView.addArrangedSubview(descriptionLabel)
stackView.axis = .vertical
stackView.distribution = .fillProportionally
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0.0).isActive = true
stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0.0).isActive = true
stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0.0).isActive = true
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0.0).isActive = true
// constrain stack view to four sides
// hold width
translatesAutoresizingMaskIntoConstraints = false
widthAnchor.constraint(equalToConstant: 100).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateText(name: String, description: String) {
nameLabel.text = name
descriptionLabel.text = description
// resize custom view to fit text in nameLabel / descriptionLabel
}
}

How to use container view programmatically

I created a ViewController, and I want to add in my ViewController a container view, here I set the container view inside my ViewController:
var containerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
return view
}()
func setUpViews() {
view.addSubview(containerView)
containerView.heightAnchor.constraint(equalToConstant: 300).isActive = true
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
containerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
}
Here I set my instance of SecondViewController in the containerView:
override func viewDidLoad() {
super.viewDidLoad()
setUpViews()
let secondViewController = SecondViewController()
secondViewController.willMove(toParent: self)
containerView.addSubview(secondViewController.view)
self.addChild(secondViewController)
secondViewController.didMove(toParent: self)
}
In my SecondViewController, I declared label and a view, I set the label in the center of the view:
let label: UILabel = {
let label = UILabel()
label.text = "Hello!"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myView)
myView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
myView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
myView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
view.addSubview(label)
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
That's what I see in my app, but I aspected to see a label in the center of the gray view.
It doesn't work like I aspected and I don't understand why.
You need to set the frame and/or constraints on the loaded view:
override func viewDidLoad() {
super.viewDidLoad()
setUpViews()
let secondViewController = SecondViewController()
secondViewController.willMove(toParent: self)
containerView.addSubview(secondViewController.view)
// set the frame
secondViewController.view.frame = containerView.bounds
// enable auto-sizing (for example, if the device is rotated)
secondViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addChild(secondViewController)
secondViewController.didMove(toParent: self)
}

UIStackView container view height based on subviews

Here is my simple example. I have 1 vertical stack view with 1 subview. I want that subviews height to be based on the intrinsic height of the label within it, so that I can maintain a dynamic height for the entire stack view. How can this be done? Thanks
I think you did it right. But here is the keys:
Don't set height for stackView.
Set label top, bottom, left, trailing constraint to view.
Run. It should be okay on simulator.
If you found label's height seems not wrapping (neither both on storyboard or simulator), then change label's Vertical Content Hugging Priority to 750.
Try this code:
class DyanmicTextLabelViewController: UIViewController {
private var didAddConstraint = false
private let label: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.required, for: .vertical)
view.setContentCompressionResistancePriority(.required, for: .vertical)
view.text = "Layout anchors let you create constraints in an easy-to-read, compact format. They expose a number of methods for creating different types of constraints, as shown in Listing 13-1."
view.numberOfLines = 0
return view
}()
private lazy var container: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
view.backgroundColor = .red
return view
}()
private lazy var stackview : UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.axis = .horizontal
view.distribution = .fill
view.addArrangedSubview(container)
return view
}()
override func loadView() {
super.loadView()
view.addSubview(stackview)
view.setNeedsUpdateConstraints()
view.backgroundColor = .white
}
override func updateViewConstraints() {
super.updateViewConstraints()
if didAddConstraint == false {
didAddConstraint = true
// stackview constraints
stackview.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
let topAnchor = stackview.topAnchor.constraint(equalTo: view.topAnchor)
topAnchor.constant = 20
topAnchor.isActive = true
stackview.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
// label constraint
// example for giving label a left padding
let labelLeft = label.leftAnchor.constraint(equalTo: container.leftAnchor)
labelLeft.constant = 16.0
labelLeft.isActive = true
label.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
label.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
}
}
}
The important part here is the initialization of stackview, label & constraint set on label
label initialization
private let label: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.required, for: .vertical)
view.setContentCompressionResistancePriority(.required, for: .vertical)
view.text = "Layout anchors let you create constraints in an easy-to-read, compact format. They expose a number of methods for creating different types of constraints, as shown in Listing 13-1."
view.numberOfLines = 0
return view
}()
stackview initialization
private lazy var stackview : UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.axis = .horizontal
view.distribution = .fill
view.addArrangedSubview(container)
return view
}()
label constraint
// label constraint
// example for giving label a left padding
let labelLeft = label.leftAnchor.constraint(equalTo: container.leftAnchor)
labelLeft.constant = 16.0
labelLeft.isActive = true
label.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
label.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
This settings could be easily translated to storyboard.

Set button width to fit dynamic button title

I have my UI structured say Level 1(UP), Level 2(DOWN) with some controls
In level 1, I have a label L1
In level 2, I have a button and label L2
In level 2 my button may be removed in runtime and I wanted my label L2 to be aligned to leading edge as L1
I'm facing two problems here
When I set my button title programmatically, I want to set my button such that its width grows when text increases and reduces its width when there is less text content. This isn't happening. Please see below screens the constraints I've in place
When I removed my button from superview, I wanted my L2 label Leading to be aligned to L1 leading. So I created a constraint from L2.leading = L1.leading and prioirty is 999
In this case, the button gets reduces its size to almost 0 even if i have text in that. Please advice me setting this up
Problem #1:
use .horizontal UIStackview for the button and text. set its distribution to .fill. For the button set contentCompression resistance priority to .required for .horizontal & set contenHugging priority to .required for .horizontal. So the Button will always wrap the text no matter what.
Problem #2:
While placing inside a stackview, you don't have to remove the button from superview. Just hide it using isHidden.
Code Demonstration
class SampleVC: UIViewController {
private var didAddConstraint = false
// Basic Views
private let label: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.text = "Label"
return view
}()
private let topButton: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.setTitle("Button", for: .normal)
view.setTitleColor(.gray, for: .highlighted)
view.backgroundColor = .green
view.setContentHuggingPriority(.required, for: .horizontal)
view.setContentCompressionResistancePriority(.required, for: .horizontal)
return view
}()
private let rightLabel: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.numberOfLines = 0
view.text = "label"
view.backgroundColor = .red
return view
}()
private lazy var stackview: UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.axis = .horizontal
view.distribution = .fill
view.addArrangedSubview(topButton)
view.addArrangedSubview(rightLabel)
return view
}()
override func loadView() {
super.loadView()
view.addSubview(label)
view.addSubview(stackview)
view.setNeedsUpdateConstraints()
view.backgroundColor = .white
}
override func updateViewConstraints() {
super.updateViewConstraints()
if didAddConstraint == false {
didAddConstraint = true
// top label
label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16.0).isActive = true
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
// stackview
stackview.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16.0).isActive = true
stackview.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 8.0).isActive = true
stackview.rightAnchor.constraint(equalToSystemSpacingAfter: view.rightAnchor, multiplier: 16.0).isActive = true
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// TEST Code
// topButton.setTitle("TEST TEST TEST", for: .normal)
// topButton.isHidden = true
}
}

Setting constant width on subview of UIStackView when axis is vertical

I have a UIScrollView that contains a UIStackView, and I add views to it and if the UIStackView needs more space than the screen has then it will scroll thanks to the UIScrollView.
I am able to set constant heights on the views, but I also need to set a specific width on them, so that they have a specific width and are also centered in the stack view.
Something like this, except the widthAnchor does not work.
import UIKit
class ViewController: UIViewController {
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.backgroundColor = .gray
return sv
}()
let stackView: UIStackView = {
let sv = UIStackView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.axis = .vertical
return sv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.addSubview(stackView)
stackView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
let view1 = UIView()
view1.backgroundColor = .red
let view2 = UIView()
view2.backgroundColor = .blue
let view3 = UIView()
view3.backgroundColor = .green
let view4 = UIView()
view4.backgroundColor = .purple
stackView.addArrangedSubview(view1)
stackView.addArrangedSubview(view2)
stackView.addArrangedSubview(view3)
stackView.addArrangedSubview(view4)
view1.heightAnchor.constraint(equalToConstant: 200).isActive = true
view2.heightAnchor.constraint(equalToConstant: 300).isActive = true
view3.heightAnchor.constraint(equalToConstant: 420).isActive = true
view4.heightAnchor.constraint(equalToConstant: 100).isActive = true
// This does not work.
// view1.widthAnchor.constraint(equalToConstant: 40).isActive = true
}
}
The alignment property on a UIStackView determines how its layout works perpendicular to its axis. By default, a UIStackView has an alignment of fill. In constraint terms, fill is like adding a constraint to (in this case) the left and right edges of the stack view for each arranged subview. These implicit constraints are likely causing your problem. Solution: set stackView.alignment = either leading, center, or trailing depending on your desired effect.

Resources