Use UIStackView as UITableViewCell's accessoryView - ios

I would like my table view cells to have multiple accessory buttons. To achieve this, I decided to add them to stack views:
extension MyTableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
cell.textLabel?.text = "Test"
cell.accessoryView = self.newStackView()
return cell
}
private func newStackView() -> UIView {
let eyeButton = UIButton(image: "eye")
let refreshButton = UIButton(image: "refresh")
let stackView = UIStackView(arrangedSubviews: [eyeButton, refreshButton])
stackView.axis = .horizontal
return stackView
}
}
fileprivate extension UIButton {
convenience init(image systemName: String) {
self.init()
self.setImage(UIImage(systemName: systemName)!, for: .normal)
self.sizeToFit()
}
}
However, the buttons do not appear.
If I use one of the buttons as the accessory view, it will in fact appear:
cell.accessoryView = UIButton(image: "eye")
Is there something wrong with the way I create the stack views?

You need to set “frame” constraints to your views
For example
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.topAnchor),
stackView.leftAnchor.constraint(equalTo: view.leftAnchor),
stackView.rightAnchor.constraint(equalTo: view.rightAnchor),
stackView.heightAnchor.constraint(equalToConstant: 10l)
])
Or
stackview.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
Follow this question

Your stackView should tell it's size
private func newStackView() -> UIView {
let eyeButton = UIButton(image: "eye")
let refreshButton = UIButton(image: "refresh")
let stackView = UIStackView(arrangedSubviews: [eyeButton, refreshButton])
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 5
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.widthAnchor.constraint(equalToConstant: 65),
stackView.heightAnchor.constraint(equalToConstant: 30)
])
return stackView
}

Related

Resizing image inside of UIButton

I have been trying to get the system images I placed inside of a UIButton to scale aspect fit, but no solutions I find online seem to work. This is what I have tried so far:
//the cells objects
var acceptButton = UIButton(type: .custom)
var declineButton = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
//add the contents and set its autolayout constraints
setAutoLayoutConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//function to set the autolayout constraints for the cell's contents
func setAutoLayoutConstraints() {
//create the stack view which will contain the accept and reject buttons
let buttonStackView = UIStackView()
buttonStackView.axis = .horizontal
buttonStackView.distribution = .fillEqually
buttonStackView.alignment = .fill
//add the buttons to the stack view
buttonStackView.addArrangedSubview(acceptButton)
buttonStackView.addArrangedSubview(declineButton)
//add the button stack view to the cell
self.addSubview(buttonStackView)
buttonStackView.translatesAutoresizingMaskIntoConstraints = false
buttonStackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
buttonStackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
buttonStackView.leadingAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
buttonStackView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
//add the button images
let addImage = UIImage(systemName: "checkmark.circle")
acceptButton.imageView?.contentMode = .scaleAspectFit
acceptButton.setImage(addImage, for: .normal)
acceptButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
acceptButton.addTarget(self, action: #selector(addButtonClicked), for: .touchUpInside)
let declineImage = UIImage(systemName: "xmark.octagon")
declineButton.imageView?.contentMode = .scaleAspectFit
declineButton.setImage(declineImage, for: .normal)
declineButton.addTarget(self, action: #selector(declineButtonClicked), for: .touchUpInside)
}
This is what I get:
(The "test test" label is just what I added for the left half of the cell's contents, can be ignored)
I have tried multiple solutions such as setting the edge insets, setting the content mode of the button and the button's image view, using a custom button, etc. but I can't seem to get the image to resized.
NOTE: When I make the image the background image with setBackgroundImage, I am able to resize the button but I can not scale aspect fit it, only fill it horizontally and vertically which is not what I am looking to do.
Any help is appreciated, thanks!!
This is a simple solution example: add first your labelTest and after that set stackView leading anchor to labelTest trailing...
this is my tableView:
class YourViewController: UIViewController, UITabBarDelegate, UITableViewDataSource, UITableViewDelegate {
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
tableView.delegate = self
tableView.dataSource = self
tableView.register(myCell.self, forCellReuseIdentifier: "cellId")
tableView.backgroundColor = .white
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! myCell
return cell
}
}
Now set my cell with arrangedSubviews and set constraints to content view (this is the correct way, not directly to cell):
class myCell: UITableViewCell {
let labelTest: UILabel = {
let label = UILabel()
label.text = "test Label"
label.backgroundColor = .red
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var acceptButton = UIButton(type: .custom)
var declineButton = UIButton(type: .custom)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
acceptButton.backgroundColor = .purple
declineButton.backgroundColor = .brown
setAutoLayoutConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//function to set the autolayout constraints for the cell's contents
func setAutoLayoutConstraints() {
contentView.addSubview(labelTest)
labelTest.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
labelTest.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
labelTest.trailingAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
labelTest.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
let buttonStackView = UIStackView(arrangedSubviews: [acceptButton, declineButton])
buttonStackView.axis = .horizontal
buttonStackView.distribution = .fillEqually
buttonStackView.translatesAutoresizingMaskIntoConstraints = false
//add the button stack view to the cell
contentView.addSubview(buttonStackView)
buttonStackView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
buttonStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
buttonStackView.leadingAnchor.constraint(equalTo: labelTest.trailingAnchor).isActive = true
buttonStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
//add the buttons images
let addImage = UIImage(systemName: "checkmark.circle")
acceptButton.imageView?.contentMode = .scaleAspectFit
acceptButton.setImage(addImage, for: .normal)
acceptButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
acceptButton.addTarget(self, action: #selector(addButtonClicked), for: .touchUpInside)
let declineImage = UIImage(systemName: "xmark.octagon")
declineButton.imageView?.contentMode = .scaleAspectFit
declineButton.setImage(declineImage, for: .normal)
declineButton.addTarget(self, action: #selector(declineButtonClicked), for: .touchUpInside)
}
}
If you want some space to left/right simply add constant to relative constraint:
labelTest.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
buttonStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
This is the results

UIImageView not resizing as circle and UILabel not resizing within StackView and Custom Collection Cell

I am trying to resize my UIImageView as a circle, however; every time I try to resize the UIImageView, which is inside a StackView along with the UILabel, I keep on ending up with a more rectangular shape. Can someone show me where I am going wrong I have been stuck on this for days? Below is my code, and what it's trying to do is add the image with the label at the bottom, and the image is supposed to be round, and this is supposed to be for my collection view controller.
custom collection view cell
import UIKit
class CarerCollectionViewCell: UICollectionViewCell {
static let identifier = "CarerCollectionViewCell"
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20);
//imageView.center = imageView.superview!.center;
imageView.contentMode = .scaleAspectFill
imageView.layer.borderWidth = 4
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.orange.cgColor
imageView.layer.cornerRadius = imageView.frame.height / 2
return imageView
}()
private let carerNamelabel: UILabel = {
let carerNamelabel = UILabel()
carerNamelabel.layer.masksToBounds = false
carerNamelabel.font = .systemFont(ofSize: 12)
carerNamelabel.textAlignment = .center
carerNamelabel.layer.frame = CGRect(x: 0, y: 0, width: 50, height: 50);
return carerNamelabel
}()
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.layer.masksToBounds = false
stackView.axis = .vertical
stackView.alignment = .center
stackView.backgroundColor = .systemOrange
stackView.distribution = .fillProportionally
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
override init(frame: CGRect) {
super.init(frame: frame)
configureContentView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func configureContentView() {
imageView.clipsToBounds = true
stackView.clipsToBounds = true
carerNamelabel.clipsToBounds = true
contentView.addSubview(stackView)
configureStackView()
}
private func configureStackView() {
allContraints()
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(carerNamelabel)
}
private func allContraints() {
setStackViewConstraint()
}
private func setStackViewConstraint() {
stackView.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true
stackView.heightAnchor.constraint(equalTo: contentView.heightAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
public func configureImage(with imageName: String, andImageName labelName: String) {
imageView.image = UIImage(named: imageName)
carerNamelabel.text = labelName
}
override func layoutSubviews() {
super.layoutSubviews()
stackView.frame = contentView.bounds
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
carerNamelabel.text = nil
}
}
Below here is my code for the CollectionViewControler
custom collection view
import UIKit
class CarerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: 120, height: 120)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.register(CarerCollectionViewCell.self, forCellWithReuseIdentifier: CarerCollectionViewCell.identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.backgroundColor = .clear
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
// Layout constraints for `collectionView`
NSLayoutConstraint.activate([
collectionView.widthAnchor.constraint(equalTo: view.widthAnchor),
collectionView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor, constant: 600),
collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 200),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
])
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CarerCollectionViewCell.identifier, for: indexPath) as! CarerCollectionViewCell
cell.configureImage(with: "m7opt04g_ms-dhoni-afp_625x300_06_July_20", andImageName: "IMAGE NO. 1")
return cell
}
}
Can somebody show or point to me what I am doing wrong, thank you
This is what I am trying to achieve
UIStackView could be tricky sometimes, you can embed your UIImageView in a UIView, and move your layout code to viewWillLayoutSubviews(), this also implys for the UILabel embed that also inside a UIView, so the containers UIViews will have a static frame for the UIStackViewto be layout correctly and whats inside them will only affect itself.

Prevent UIStackView from compressing UITableView

I am adding a UITableView into vertical UIStackView. That vertical UIStackView is within a UIScrollView.
However the table is not displaying unless I force an explicit Height constraint on it which I obviously don't want to do.
According to this SO question and answer UITableView not shown inside UIStackView this is because "stackview tries to compress content as much as possible"
If I add a UILabel to the StackView it is displayed fine. There is something specific about the UITableView that means it is not. I am using Xamarin and creating the UITableView in code
this.recentlyOpenedPatientsTable = new UITableView()
{
RowHeight = UITableView.AutomaticDimension,
EstimatedRowHeight = 44.0f,
AllowsMultipleSelectionDuringEditing = false,
TranslatesAutoresizingMaskIntoConstraints = false,
Editing = false,
BackgroundColor = UIColor.Clear,
TableFooterView = new UIView(),
ScrollEnabled = false,
};
The UIScrollView is pinned to the Top, Bottom, Left and Right of the View and works fine. It takes the Height I expect.
I have tried both the suggestions in this SO question and neither have worked. I find it odd that I cannot find others having this issue.
Any other suggestions?
Here is a very basic example, using a UITableView subclass to make it auto-size its height based on its content.
The red buttons (in a horizontal stack view) are the first arranged subView in the vertical stack view.
The table is next (green background for the cells' contentView, yellow background for a multi-line label).
And the last arranged subView is a cyan background UILabel:
Note that the vertical stack view is constrained 40-pts from Top, Leading and Trailing, and at least 40-pts from the Bottom. If you add enough rows to the table to exceed the available height, you'll have to scroll to see the additional rows.
//
// TableInStackViewController.swift
//
// Created by Don Mag on 6/24/19.
//
import UIKit
final class ContentSizedTableView: UITableView {
override var contentSize:CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
class TableInStackCell: UITableViewCell {
let theLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.textAlignment = .left
v.numberOfLines = 0
return v
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .green
contentView.addSubview(theLabel)
NSLayoutConstraint.activate([
theLabel.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: 0.0),
theLabel.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: 0.0),
theLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: 0.0),
theLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: 0.0),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TableInStackViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let theStackView: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .vertical
v.alignment = .fill
v.distribution = .fill
v.spacing = 8
return v
}()
let addButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.setTitle("Add a Row", for: .normal)
v.backgroundColor = .red
return v
}()
let deleteButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.setTitle("Delete a Row", for: .normal)
v.backgroundColor = .red
return v
}()
let buttonsStack: UIStackView = {
let v = UIStackView()
v.axis = .horizontal
v.alignment = .fill
v.distribution = .fillEqually
v.spacing = 20
return v
}()
let theTable: ContentSizedTableView = {
let v = ContentSizedTableView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let bottomLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
v.textAlignment = .center
v.numberOfLines = 0
v.text = "This label is the last element in the stack view."
// prevent label from being compressed when the table gets too tall
v.setContentCompressionResistancePriority(.required, for: .vertical)
return v
}()
var theTableData: [String] = [
"Content Sized Table View",
"This row shows that the cell heights will auto-size, based on the cell content (multi-line label in this case).",
"Here is the 3rd default row",
]
var minRows = 1
let reuseID = "TableInStackCell"
override func viewDidLoad() {
super.viewDidLoad()
minRows = theTableData.count
view.addSubview(theStackView)
NSLayoutConstraint.activate([
// constrain stack view 40-pts from top, leading and trailing
theStackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
theStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
theStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
// constrain stack view *at least* 40-pts from bottom
theStackView.bottomAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40.0),
])
buttonsStack.addArrangedSubview(addButton)
buttonsStack.addArrangedSubview(deleteButton)
theStackView.addArrangedSubview(buttonsStack)
theStackView.addArrangedSubview(theTable)
theStackView.addArrangedSubview(bottomLabel)
theTable.delegate = self
theTable.dataSource = self
theTable.register(TableInStackCell.self, forCellReuseIdentifier: reuseID)
addButton.addTarget(self, action: #selector(addRow), for: .touchUpInside)
deleteButton.addTarget(self, action: #selector(deleteRow), for: .touchUpInside)
}
#objc func addRow() -> Void {
// add a row to our data source
let n = theTableData.count - minRows
theTableData.append("Added Row: \(n + 1)")
theTable.reloadData()
}
#objc func deleteRow() -> Void {
// delete a row from our data source (keeping the original rows intact)
let n = theTableData.count
if n > minRows {
theTableData.remove(at: n - 1)
theTable.reloadData()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return theTableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath) as! TableInStackCell
cell.theLabel.text = theTableData[indexPath.row]
return cell
}
}

Why UICollectionView is not responding at all?

I'm setting up a UICollectionView inside a ViewController. However, it won't respond to any user interaction, didSelectItemAt function is not getting called and I am unable to scroll it.
I have set the DataSource and Delegate properly inside the viewDidLoad(). Here is my code:
class WelcomeController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let padding: CGFloat = 30
var sources = [Source]()
let sourceCellId = "sourceCellId"
func fetchSources() {
ApiSourceService.sharedInstance.fetchSources() { (root: Sources) in
self.sources = root.source
self.sourceCollectionView.reloadData()
}
}
let backgroundImage: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "background")
iv.contentMode = .scaleAspectFill
iv.translatesAutoresizingMaskIntoConstraints = false
iv.clipsToBounds = false
return iv
}()
let overlayView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
return view
}()
let logo: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "mylogo")
iv.translatesAutoresizingMaskIntoConstraints = false
iv.clipsToBounds = false
return iv
}()
let defaultButton: UIButton = {
let ub = UIButton()
ub.translatesAutoresizingMaskIntoConstraints = false
ub.setTitle("Inloggen met E-mail", for: .normal)
ub.setImage(UIImage(named: "envelope"), for: .normal)
ub.imageEdgeInsets = UIEdgeInsetsMake(15, 0, 15, 0)
ub.imageView?.contentMode = .scaleAspectFit
ub.contentHorizontalAlignment = .left
ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 16)
ub.backgroundColor = .cuOrange
return ub
}()
let continueWithoutButton: UIButton = {
let ub = UIButton()
ub.translatesAutoresizingMaskIntoConstraints = false
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "Doorgaan zonder in te loggen")
let textRange = NSMakeRange(0, attributedString.length)
attributedString.setColor(color: .cuOrange, forText: "Doorgaan")
ub.setAttributedTitle(attributedString, for: .normal)
ub.contentHorizontalAlignment = .center
ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 16)
ub.titleLabel?.textColor = .white
return ub
}()
let sourceCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.backgroundColor = .white
return cv
}()
let termsButton: UIButton = {
let ub = UIButton()
ub.translatesAutoresizingMaskIntoConstraints = false
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "Met het maken van een account \nof bij inloggen, ga ik akkoord \nmet servicevoorwaarden.")
let textRange = NSMakeRange(0, attributedString.length)
attributedString.setColor(color: .cuOrange, forText: "servicevoorwaarden")
ub.setAttributedTitle(attributedString, for: .normal)
ub.contentHorizontalAlignment = .center
ub.contentVerticalAlignment = .bottom
ub.titleLabel?.lineBreakMode = .byWordWrapping
ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 14)
ub.titleLabel?.textColor = .white
ub.titleLabel?.textAlignment = .center
return ub
}()
override func viewDidLoad() {
super.viewDidLoad()
fetchSources()
sourceCollectionView.dataSource = self
sourceCollectionView.delegate = self
sourceCollectionView.register(SourceCell.self, forCellWithReuseIdentifier: sourceCellId)
view.addSubview(backgroundImage)
view.addSubview(overlayView)
backgroundImage.addSubview(termsButton)
backgroundImage.addSubview(logo)
backgroundImage.addSubview(sourceCollectionView)
backgroundImage.widthAnchor.constraint(lessThanOrEqualToConstant: 375).isActive = true
backgroundImage.heightAnchor.constraint(lessThanOrEqualToConstant: 667).isActive = true
backgroundImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
backgroundImage.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
logo.centerXAnchor.constraint(equalTo: backgroundImage.centerXAnchor).isActive = true
logo.topAnchor.constraint(equalTo: backgroundImage.topAnchor, constant: padding).isActive = true
logo.widthAnchor.constraint(equalToConstant: 107).isActive = true
logo.heightAnchor.constraint(equalToConstant: 100).isActive = true
sourceCollectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
sourceCollectionView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(padding*1.5)).isActive = true
sourceCollectionView.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: padding).isActive = true
sourceCollectionView.bottomAnchor.constraint(equalTo: termsButton.topAnchor, constant: -(padding*2)).isActive = true
termsButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true
termsButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
termsButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(padding*2)).isActive = true
termsButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
sourceCollectionView.reloadData()
}
#objc func closeWelcomeController() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.switchViewControllers()
self.dismiss(animated: true, completion: {
})
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = self.sourceCollectionView.frame.width
let height = CGFloat(50)
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sources.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print(sources[indexPath.item].feed_name)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: sourceCellId, for: indexPath) as! SourceCell
cell.preservesSuperviewLayoutMargins = true
cell.source = sources[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selecting")
}}
Anyone knows what I am doing wrong here?
I hope there isn't just a "dumb" error inside the code why it's not working, but it's been eating my brain for the past few hours.
It seems that it is inappropriate to add sourceCollectionView as a subview in backgroundImage which is UIImageView! Logically, image view doesn't represent a container view (such as UIView UIStackView, UIScrollView) i.e even if the code lets you do that, it still non-sensible; Furthermore, even if adding a subview to an image view is ok (which is not), image views by default are user interaction disabled (userInteractionEnabled is false by default for image views), that's why you are unable to even scroll the collection view, it is a part (subview) of a disabled user interaction component.
In your viewDidLoad(), you are implementing:
backgroundImage.addSubview(termsButton)
backgroundImage.addSubview(logo)
backgroundImage.addSubview(sourceCollectionView)
Don't do this, instead, add them to main view of the view controller:
view.addSubview(termsButton)
view.addSubview(logo)
view.addSubview(sourceCollectionView)
For the purpose of checking if its the reason of the issue, at least do it for the collection view (view.addSubview(sourceCollectionView)).
And for the purpose of organizing the hierarchy of the view (which on is on top of the other), you could use both: bringSubview(toFront:) or sendSubview(toBack:). For instance, after adding the collection view into the view, you might need to:
view.bringSubview(toFront: sourceCollectionView)
to make sure that the collection view is on top of all components.
I see you add sourceCollectionView to subview of backgroundImage. Your backgroundImage is UIImageView so UIImageView doesn't have user interaction except you need to enable it. The problem of your code is
backgroundImage.addSubview(sourceCollectionView)
For my suggestion you should create UIView or other views that can interact with user interaction. It will work fine.

CollectionView Disappears within StackView (Swift)

I'm trying to achieve the stackView arrangement shown in the middle of this figure:, but for some reason the top stack, containing a collectionView, disappears when using: a .fill distribution
stackView.distribution = .fill (stack containing collectionView disappears)
stackView.distribution = .fillEqually (collectionView appears fine in stackView)
I've been struggling with this for days, and you'll see residues in my commented out sections: setting compressionResistance/hugging priorities, attempting to change the intrinsic height, changing .layout.itemSize of UICollectionViewFlowLayout(), etc... Nothing works in my hands. The code here will run if you simply paste it in and associate it with an empty UIViewController. The top, collectionView stack contains a pickerView, and the stacks below that are a pageControllView, subStack of buttons, and a UIView. It all works fine in the .fillEqually distribution, so this is purely a layout issue. Much Thanks!
// CodeStackVC2
// Test of programmatically generated stack views
// Output: nested stack views
// To make it run:
// 1) Assign the blank storyboard VC as CodeStackVC2
// 2) Move the "Is Inital VC" arrow to the blank storyboard
import UIKit
class CodeStackVC2: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
let fruit = ["Apple", "Orange", "Plum", "Qiwi", "Banana"]
let veg = ["Lettuce", "Carrot", "Celery", "Onion", "Brocolli"]
let meat = ["Beef", "Chicken", "Ham", "Lamb"]
let bread = ["Wheat", "Muffin", "Rye", "Pita"]
var foods = [[String]]()
let button = ["bread","fruit","meat","veg"]
var sView = UIStackView()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
foods = [fruit, veg, meat, bread]
setupViews()
}
//MARK: Views
lazy var cView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
layout.itemSize = CGSize(width: self.view.frame.width, height: 120)
let cv = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
cv.backgroundColor = UIColor.lightGray
cv.isPagingEnabled = true
cv.dataSource = self
cv.delegate = self
cv.isUserInteractionEnabled = true
// var intrinsicContentSize: CGSize {
// return CGSize(width: UIViewNoIntrinsicMetric, height: 120)
// }
return cv
}()
lazy var pageControl: UIPageControl = {
let pageC = UIPageControl()
pageC.numberOfPages = self.foods.count
pageC.pageIndicatorTintColor = UIColor.darkGray
pageC.currentPageIndicatorTintColor = UIColor.white
pageC.backgroundColor = .lightGray
pageC.addTarget(self, action: #selector(changePage(sender:)), for: UIControlEvents.valueChanged)
// pageC.setContentHuggingPriority(900, for: .vertical)
// pageC.setContentCompressionResistancePriority(100, for: .vertical)
return pageC
}()
var readerView: UIView = {
let rView = UIView()
rView.backgroundColor = UIColor.brown
// rView.setContentHuggingPriority(100, for: .vertical)
// rView.setContentCompressionResistancePriority(900, for: .vertical)
return rView
}()
func makeButton(_ name:String) -> UIButton{
let newButton = UIButton(type: .system)
let img = UIImage(named: name)?.withRenderingMode(.alwaysTemplate)
newButton.setImage(img, for: .normal)
newButton.contentMode = .scaleAspectFit
newButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleButton)))
newButton.isUserInteractionEnabled = true
newButton.backgroundColor = .orange
return newButton
}
//Make a 4-item vertical stackView containing
//cView,pageView,subStackof 4-item horiz buttons, readerView
func setupViews(){
cView.register(FoodCell.self, forCellWithReuseIdentifier: cellId)
//generate an array of buttons
var buttons = [UIButton]()
for i in 0...foods.count-1 {
buttons += [makeButton(button[i])]
}
let subStackView = UIStackView(arrangedSubviews: buttons)
subStackView.axis = .horizontal
subStackView.distribution = .fillEqually
subStackView.alignment = .center
subStackView.spacing = 20
//set up the stackView
let stackView = UIStackView(arrangedSubviews: [cView,pageControl,subStackView,readerView])
stackView.axis = .vertical
//.fillEqually works, .fill deletes cView, .fillProportionally & .equalSpacing delete cView & readerView
stackView.distribution = .fillEqually
stackView.alignment = .fill
stackView.spacing = 5
//Add the stackView using AutoLayout
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 5).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func handleButton() {
print("button pressed")
}
//pageControl page changer
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * cView.frame.size.width
cView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}
//MARK: horizontally scrolling Chapter collectionView
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// let scrollBarLeft = CGFloat(scrollView.contentOffset.x) / CGFloat(book.chap.count + 1)
// let scrollBarWidth = CGFloat( menuBar.frame.width) / CGFloat(book.chap.count + 1)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let index = targetContentOffset.pointee.x / view.frame.width
pageControl.currentPage = Int(index) //change PageControl indicator
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return foods.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FoodCell
cell.foodType = foods[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 120)
}
}
class FoodCell:UICollectionViewCell, UIPickerViewDelegate, UIPickerViewDataSource {
var foodType: [String]? {
didSet {
pickerView.reloadComponent(0)
pickerView.selectRow(0, inComponent: 0, animated: true)
}
}
lazy var pickerView: UIPickerView = {
let pView = UIPickerView()
pView.frame = CGRect(x:0,y:0,width:Int(pView.bounds.width), height:Int(pView.bounds.height))
pView.delegate = self
pView.dataSource = self
pView.backgroundColor = .darkGray
return pView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
backgroundColor = .clear
addSubview(pickerView)
addConstraintsWithFormat("H:|[v0]|", views: pickerView)
addConstraintsWithFormat("V:|[v0]|", views: pickerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if let count = foodType?.count {
return count
} else {
return 0
}
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
pickerLabel.font = UIFont.systemFont(ofSize: 15)
pickerLabel.textAlignment = .center
pickerLabel.adjustsFontSizeToFitWidth = true
if let foodItem = foodType?[row] {
pickerLabel.text = foodItem
pickerLabel.textColor = .white
return pickerLabel
} else {
print("chap = nil in viewForRow")
return UIView()
}
}
}
The problem is that you have a stack view with a fixed height that contains two views (cView and readerView) that have no intrinsic content size. You need to tell the layout engine how it should size those views to fill the remaining space in the stack view.
It works when you use a .fillEqually distribution because you are telling the layout engine to make all four views in the stack view have an equal height. That defines a height for both the cView and readerView.
When you use a .fill distribution there is no way to determine how high the cView and readerView should be. The layout is ambiguous until you add more constraints. The content priorities do nothing as those views have no intrinsic size that can be stretched or squeezed. You need to set the height of one of the views with no intrinsic size and the other will take the remaining space.
The question is how high should the collection view be? Do you want it to be the same size as the reader view or maybe some proportion of the container view?
For example, suppose your design calls for the collection view to be 25% of the height of the container view with the readerView using the remaining space (the two other views are at their natural intrinsic content size). You could add the following constraint:
NSLayoutConstraint.activate([
cView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25)
])
A Simpler Example
To reduce the layout to its most basic elements. You have a stack view pinned to its superview with four arranged subviews two of which have no intrinsic content size. For example, here is a view controller with two plain UIView, a label and a button:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
private func setupViews() {
let blueView = UIView()
blueView.backgroundColor = .blue
let titleLabel = UILabel()
titleLabel.text = "Hello"
let button = UIButton(type: .system)
button.setTitle("Action", for: .normal)
let redView = UIView()
redView.backgroundColor = .red
let stackView = UIStackView(arrangedSubviews: [blueView, titleLabel, button, redView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 8
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
stackView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
blueView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25)
])
}
}
Here is how it looks on an iPhone in portrait with the blue view using 25% of the vertical space:
UIStackView works well with arranged subviews that are UIView but not directly with UICollectionView.
I suggest you put all your subviews items inside a UIView before stack them in a UIStackView, also you can use .fill distribution without use intrinsic content size, use instead constraints to make your subviews proportional as you need.
This solution also work seamless with autolayout without force translatesAutoresizingMaskIntoConstraints = false which make you less compliant with trait changes if you know what I mean.
/GM
Set the top, bottom, leading and trailing constraint of desired controls inside xib or storyboard.
Provide distribution of stack .fill.
Then provide height constraint of all stacks in Xib or storyboard.
Then set appropriate heights for every stacks inside code.
Hopefully it works for you.
I had the same issue, and for me it worked when I gave height and width constraints to the collection view which was placed inside the stack view.
I experienced this behavior with Xamarin CollectionView and tracked it down to an interaction being made with the CollectionView after the page was removed from the MainPage as the result of a web api call. Even blocking that, though it still had issues reloading the page. I finally resolved to clearing the collection list when the page is about to be hidden and saving a backup copy of the items, then on display of the page, running an async task that waited 10ms and then reinstalled the items. Failing to clear the list or installing items into the list immediately upon redisplay both leads to the error. The following shows in the console list and the CollectionView seems to flag itself to longer try to work after this message:
2022-04-16 19:56:33.760310-0500 .iOS[30135:2117558] The behavior of the UICollectionViewFlowLayout is not defined because:
2022-04-16 19:56:33.760454-0500 .iOS[30135:2117558] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2022-04-16 19:56:33.760581-0500 .iOS[30135:2117558] Please check the values returned by the delegate.
2022-04-16 19:56:33.760754-0500 .iOS[30135:2117558] The relevant UICollectionViewFlowLayout instance is <Xamarin_Forms_Platform_iOS_ListViewLayout: 0x7f99e4c4e890>, and it is attached to <UICollectionView: 0x7f99e562a000; frame = (0 0; 420 695); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x6000015ad9b0>; layer = <CALayer: 0x600005be5860>; contentOffset: {0, 0}; contentSize: {0, 0}; adjustedContentInset: {0, 0, 0, 0}; layout: <Xamarin_Forms_Platform_iOS_ListViewLayout: 0x7f99e4c4e890>; dataSource: <Xamarin_Forms_Platform_iOS_GroupableItemsViewController_1: 0x7f99e4c7ace0>>.
2022-04-16 19:56:33.760829-0500 .iOS[30135:2117558] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.

Resources