I have a tableView with cells that contain UiCollectionView. My didSelect tableView's delegate isn't called when I touch the cell on the collectionView.
I think it's my collectionView that get the touch instead. Do you have any elegant solution to keep the scroll enabled on my collectionView but disable the selection and pass it to the tableview ?
Here is my tableView declaration :
private lazy var tableView:UITableView = { [weak self] in
$0.register(TestTableViewCell.self, forCellReuseIdentifier: "identifier")
$0.delegate = self
$0.dataSource = self
return $0
}(UITableView())
Here are my delegate and dataSource methods:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! TestTableViewCell
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print(indexPath)
}
And here is my cell :
public class TestTableViewCell : UITableViewCell {
private lazy var collectionViewFlowLayout:UICollectionViewFlowLayout = {
$0.scrollDirection = .horizontal
$0.minimumLineSpacing = 0
$0.minimumInteritemSpacing = 0
return $0
}(UICollectionViewFlowLayout())
private lazy var collectionView:UICollectionView = {
$0.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "identifier")
$0.delegate = self
$0.dataSource = self
return $0
}(UICollectionView(frame: .zero, collectionViewLayout: collectionViewFlowLayout))
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(collectionView)
collectionView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cell:"identifier", for: indexPath) as! cell:UICollectionViewCell
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.frame.size
}
}
If you spot any compilation error, excuse me, this is an anonymized copy/past. My app is running without error.
If you want an example of what I'm trying to do you can check AirBnb's app. TableView with some houses with cells and inside, pictures collectionView. Il you touch the collectionView, the tableView select the cell...
Thanks
I don't believe there is a "direct" way to do what you're asking. The collection view will respond to the gestures, so they can't "flow through" to the table view / cells without using a closure or protocol/delegate pattern.
Here's one approach...
We subclass UICollectionView and, on touchesBegan call a closure to tell the table view to select the row.
We can also implement scrollViewWillBeginDragging to select the row on collection view scroll, in addition to collection view "tap."
So...
View Controller class
class TableColTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// number of items in the collection view for each row
let myData: [Int] = [
12, 15, 8, 21, 17, 14,
16, 10, 5, 13, 20, 19,
]
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
tableView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
tableView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
tableView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
])
tableView.register(SomeTableCell.self, forCellReuseIdentifier: "someTableCell")
tableView.dataSource = self
tableView.delegate = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "someTableCell", for: indexPath) as! SomeTableCell
cell.rowTitleLabel.text = "Row \(indexPath.row)"
cell.numItems = myData[indexPath.row]
// closure for the cell to tell us to select it
// because its collection view was tapped
cell.passThroughSelect = { [weak self] theCell in
guard let self = self,
let pth = self.tableView.indexPath(for: theCell)
else { return }
self.tableView.selectRow(at: pth, animated: true, scrollPosition: .none)
// selecting a row programmatically does NOT trigger didSelectRowAt
// so we'll call our own did select func
self.myDidSelect(pth)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// pass this on to our own did select func
// so it matches what happens when programmatically selecting the row
myDidSelect(indexPath)
}
func myDidSelect(_ indexPath: IndexPath) {
print("Table View - didSelectRowAt", indexPath)
// do something because the row was selected
}
}
Table View Cell class
class SomeTableCell: UITableViewCell {
// callback closure
var passThroughSelect: ((UITableViewCell) -> ())?
var rowTitleLabel = UILabel()
var collectionView: SubCollectionView!
var numItems: Int = 0 {
didSet {
collectionView.reloadData()
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
let fl = UICollectionViewFlowLayout()
fl.scrollDirection = .horizontal
fl.estimatedItemSize = CGSize(width: 120.0, height: 52.0)
fl.minimumLineSpacing = 12
fl.minimumInteritemSpacing = 12
collectionView = SubCollectionView(frame: .zero, collectionViewLayout: fl)
rowTitleLabel.translatesAutoresizingMaskIntoConstraints = false
collectionView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(rowTitleLabel)
contentView.addSubview(collectionView)
let g = contentView.layoutMarginsGuide
// avoid auto-layout complaints
let c = collectionView.heightAnchor.constraint(equalToConstant: 60.0)
c.priority = .required - 1
NSLayoutConstraint.activate([
rowTitleLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
rowTitleLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
rowTitleLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
rowTitleLabel.heightAnchor.constraint(equalToConstant: 30.0),
collectionView.topAnchor.constraint(equalTo: rowTitleLabel.bottomAnchor, constant: 4.0),
collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
collectionView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
c,
])
collectionView.register(SomeCollectionCell.self, forCellWithReuseIdentifier: "someCollectionCell")
collectionView.dataSource = self
collectionView.delegate = self
collectionView.passThroughTouch = { [weak self] in
guard let self = self else { return }
self.passThroughSelect?(self)
}
collectionView.backgroundColor = .systemYellow
}
}
extension SomeTableCell: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "someCollectionCell", for: indexPath) as! SomeCollectionCell
cell.label.text = "Cell \(indexPath.item)"
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Collection View - didSelectItemAt", indexPath)
}
}
extension SomeTableCell: UIScrollViewDelegate {
// if you only want the table cell selected on TAP, don't implement this
// if you want the table cell selected on CollectionView SCROLL, implement this
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.passThroughSelect?(self)
}
}
UICollectionView subclass
class SubCollectionView: UICollectionView {
var passThroughTouch: (() -> ())?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// this allows the collection view cell to be selected
super.touchesBegan(touches, with: event)
// this tells the controller (the table view cell)
// that the collection view was tapped
passThroughTouch?()
}
}
UICollectionView Cell class
class SomeCollectionCell: UICollectionViewCell {
var label = UILabel()
var styleView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
styleView.translatesAutoresizingMaskIntoConstraints = false
label.translatesAutoresizingMaskIntoConstraints = false
styleView.addSubview(label)
contentView.addSubview(styleView)
let g = contentView
NSLayoutConstraint.activate([
styleView.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
styleView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
styleView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
styleView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
label.topAnchor.constraint(equalTo: styleView.topAnchor, constant: 8.0),
label.leadingAnchor.constraint(equalTo: styleView.leadingAnchor, constant: 8.0),
label.trailingAnchor.constraint(equalTo: styleView.trailingAnchor, constant: -8.0),
label.bottomAnchor.constraint(equalTo: styleView.bottomAnchor, constant: -8.0),
])
label.textColor = .white
styleView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
styleView.layer.borderColor = UIColor.white.cgColor
styleView.layer.borderWidth = 1
styleView.layer.cornerRadius = 6
}
override var isSelected: Bool {
didSet {
label.textColor = isSelected ? .red : .white
styleView.backgroundColor = isSelected ? UIColor(white: 0.95, alpha: 1.0) : UIColor(white: 0.5, alpha: 1.0)
styleView.layer.borderColor = isSelected ? UIColor.red.cgColor : UIColor.white.cgColor
}
}
}
You can do the following
First in first, print something in didSelectItem of your collectionView delegate, to make ensure that your collectionView cell is tapped.
add a delegate property in your UICollectionViewClass and call the delegate in the DidSelectItem if the step 1 is performing correctly.
In your UITableViewController, you have a function cellForRowAtIndexPath, here add the delegate property for the associate cell.
If you can print something in your delegate function, then you are at your last step. Call super.didSelect..with your indexPath, because now you have everything to call didSelect manually.
Maybe you would like to try allowsSelection property of UICollectionView. If you set this property false, your collection view cells are not selected any more.
And I think tableView didSelect can capture user interaction. If UITableView still can not capture didSelect, you can give delegate to collectionView and fire it once it's tapped by adding a tap gesture onto UICollectionView.
Related
I am using two nested collection views. I have added the ChildCollectionView to the ParentCollectionViewCell, and ChildCollectionView have 3 cells in it but the ParentCollectionViewCell does not adjust the frame of the cell as per the content.
Here's the code,
ParentCollectionView
class ViewController: UIViewController {
var parentCollectionView: UICollectionView = {
let _collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
return _collectionView
}()
let id = "ParentCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(parentCollectionView)
parentCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
parentCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
parentCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
parentCollectionView.topAnchor.constraint(equalTo: view.topAnchor),
parentCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
parentCollectionView.dataSource = self
parentCollectionView.register(UINib(nibName: id, bundle: nil), forCellWithReuseIdentifier: id)
if let flowLayout = parentCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath) as! ParentCollectionViewCell
cell.backgroundColor = .red
return cell
}
}
ParentCollectionViewCell
class ParentCollectionViewCell: UICollectionViewCell {
var childCollectionView: UICollectionView = {
let _collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
return _collectionView
}()
let reuseId = "ChildCollectionViewCell"
private let data = ["ChildCell1","ChildCell2","ChildCell3"]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setupViews()
}
func setupViews() {
contentView.addSubview(childCollectionView)
childCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
childCollectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
childCollectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
childCollectionView.topAnchor.constraint(equalTo: contentView.topAnchor),
childCollectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
childCollectionView.widthAnchor.constraint(equalToConstant: 360)
])
childCollectionView.dataSource = self
childCollectionView.register(UINib(nibName: reuseId, bundle: nil), forCellWithReuseIdentifier: reuseId)
if let flowLayout = childCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
}
extension ParentCollectionViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) as! ChildCollectionViewCell
cell.backgroundColor = .gray
cell.setupViews()
return cell
}
}
ChildCollectionViewCell
class ChildCollectionViewCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupViews() {
let label = UILabel()
label.text = "Child Collection"
label.numberOfLines = 0
label.font = label.font.withSize(50)
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
label.topAnchor.constraint(equalTo: contentView.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
}
Current Output
Current Output
Expected Output
Expected Output
You need to adjust your parent collection height with this line
ChildCollectionView.collectionViewLayout.collectionViewContentSize.height
Please take a look at this it will help you to understand how to handle your parent collection height with childCollection Content
How to adjust height of UICollectionView to be the height of the content size of the UICollectionView?
I want to implement UITableView's UISwipeActionsConfiguration for a UICollectionView. In order to do so, I am using SwipeCellKit - github
My UICollectionView adopts to the SwipeCollectionViewCellDelegate protocol. And the cell inherits from SwipeCollectionViewCell.
ViewController with UICollectionView
class SwipeViewController: UIViewController {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.register(SwipeableCollectionViewCell.self, forCellWithReuseIdentifier: SwipeableCollectionViewCell.identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 4, right: 0)
collectionView.backgroundColor = UIColor(white: 0.97, alpha: 1)
collectionView.dataSource = self
collectionView.delegate = self
return collectionView
}()
var items: [String] = {
var items = [String]()
for i in 1 ..< 20 {
items.append("Item \(i)")
}
return items
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.setConstraints(topAnchor: view.topAnchor,
leadingAnchor: view.leadingAnchor,
bottomAnchor: view.bottomAnchor,
trailingAnchor: view.trailingAnchor,
leadingConstant: 10,
trailingConstant: 10)
}
}
extension SwipeViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 80)
}
}
extension SwipeViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SwipeableCollectionViewCell.identifier, for: indexPath) as! SwipeableCollectionViewCell
cell.backgroundColor = BackgroundColor.colors[indexPath.row]
cell.delegate = self
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
extension SwipeViewController: SwipeCollectionViewCellDelegate {
func collectionView(_ collectionView: UICollectionView, editActionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
}
return [deleteAction]
}
}
SwipeCollectionViewCell
class SwipeableCollectionViewCell: SwipeCollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(nameLabel)
nameLabel.setConstraints(topAnchor: self.topAnchor,
leadingAnchor: self.leadingAnchor,
bottomAnchor: self.bottomAnchor,
trailingAnchor: self.trailingAnchor)
self.backgroundColor = .white
}
static let identifier = "TaskListTableViewCell"
private let nameLabel: UILabel = {
let label = UILabel()
label.text = "Simulator user has requested new graphics quality"
label.numberOfLines = 0
return label
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
After doing so, when I swipe the cell, the deleteAction overlaps with the content of the cell.
As you see in the screenshot, the cell's content overlaps with the deleteAction text.
Update
setConstraints sets views's translatesAutoresizingMaskIntoConstraints to false
You must add nameLabel to contentView.
Change
self.addSubview(nameLabel)
nameLabel.setConstraints(topAnchor: self.topAnchor,
leadingAnchor: self.leadingAnchor,
bottomAnchor: self.bottomAnchor,
trailingAnchor: self.trailingAnchor)
to
self.contentView.addSubview(nameLabel)
nameLabel.setConstraints(topAnchor: self.contentView.topAnchor,
leadingAnchor: self.contentView.leadingAnchor,
bottomAnchor: self.contentView.bottomAnchor,
trailingAnchor: self.contentView.trailingAnchor)
Result:
I have a list of sensors in a collectionView inside a UIView class called MyCropView where I show some data about that crop.
Im trying to change the value of some sensors like the icon and the background color on each click.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let myCropCard = collectionView.superview as! MyCropCard
let sensor = myCropCard.sensors[indexPath.row]
let cell = myCropCard.superview
//Change the color and icon of the sensors
if let cell = collectionView.cellForItem(at: indexPath) as? MyCollectionViewCell {
//Previous cell in grey
if !self.lastSelectedIndexPath.isEmpty {
let lastCell = collectionView.cellForItem(at: self.lastSelectedIndexPath) as? MyCollectionViewCell
lastCell?.imageView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
lastCell?.imageView.image = UIImage(named: self.lastSelectedImageName )
}
//Makes sensor green onSelect
cell.imageView.backgroundColor = UIColor(red: 0.882, green: 0.95, blue: 0.882, alpha: 1.0)
cell.imageView.image = UIImage(named: sensor.getType() )
self.lastSelectedIndexPath = indexPath
self.lastSelectedImageName = String(format: "%#_deactivated", sensor.getType())
}
//Show all the alerts of each sensor
for alert:Alert in sensor.getAlerts() {
let viewSensor = cell?.viewWithTag(300) as! SensorView
viewSensor.lblSensor.text = sensor.getTipo()
viewSensor.lblBotLog.text = alerta.getNombreDispositivo()
viewSensor.lblMin.text = String(format: "MIN %.0f", alert.getMin())
viewSensor.lblMax.text = String(format: "MAX %.0f", alert.getMax())
viewSensor.btnDel.tag = Int(alert.getId() + 1000)
viewSensor.btnDel.addTarget(
self,
action: #selector( viewSensor.deleteAlert(_:) ),
for: .touchUpInside
)
viewSensor.isHidden = false
}
}
That collectionView is the list of sensors we have. It works fine with 1st MyCropCard, But doesn't for multiple MyCropCards. Superview takes the first cropCard of them all, not the collectionView's parent.
I would like to know how can I correctly have the parent of the selected collectionView?
Your code is cluttered with unneccessary logic-related codes, which are probably unrelated to the issue.
Also, extensive use of tags are making the code unscalable and hard to maintain, so it probably needs a heavy refactoring.
The following code is basically a MWE for what you want to achieve (If I misunderstood your issue, let me know).
To explain the code, this is a custom tableViewCell:
class TableViewCell: UITableViewCell {
var collectionView: UICollectionView? {
didSet {
guard let collectionView = collectionView else { return }
contentView.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .white
setupCollectionViewLayout(collectionView)
}
}
private func setupCollectionViewLayout(_ collectionView: UICollectionView) {
NSLayoutConstraint.activate([
collectionView.leadingAnchor
.constraint(equalTo: contentView.leadingAnchor),
collectionView.trailingAnchor
.constraint(equalTo: contentView.trailingAnchor),
collectionView.topAnchor
.constraint(equalTo: contentView.topAnchor),
collectionView.bottomAnchor
.constraint(equalTo: contentView.bottomAnchor),
])
}
}
setupCollectionViewLayout simply enables AutoLayout. collectionView will be later added when a tableViewCell instance is dequeued.
class CollectionViewCell: UICollectionViewCell {}
class ViewController: UIViewController {
private var lastSelectedCollectionViewCell: CollectionViewCell?
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(tableView)
setupTableViewLayout(tableView)
}
private func setupTableViewLayout(_ tableView: UITableView) {
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
}
tableView is added as the view is loaded, and AutoLayout constraints are added by setupTableViewLayout.
Note that you keep a copy of the last index path, but I think it is better and simpler to keep a reference to the cell itself.
In UITableViewDataSource extension:
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "cell",
for: indexPath) as! TableViewCell
guard cell.collectionView == nil else { return cell }
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: UICollectionViewFlowLayout())
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "cell")
cell.collectionView = collectionView
return cell
}
}
extension ViewController: UITableViewDelegate {}
I add a collectionView only if it doesn't already exist in a tableViewCell.
collectionView assigns dataSource and delegate as self, though it would be better if there is an extra modelController object.
UITableViewDelegate is empty.
Now extensions for the collectionViews:
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = .gray
return cell
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
lastSelectedCollectionViewCell?.backgroundColor = .gray
if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell {
cell.backgroundColor = .yellow
lastSelectedCollectionViewCell = cell
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 20, height: 20)
}
}
The important part is collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath), and the others are just boilerplate code.
When a collectionViewCell is selected, the self.lastSelectedCollectionViewCell's color turns back to gray, and the newly selected cell is assigned to lastSelectedCollectionViewCell, after its backgroundColor changed.
The following is the entire code you can run in Playground:
import UIKit
import PlaygroundSupport
class TableViewCell: UITableViewCell {
var collectionView: UICollectionView? {
didSet {
guard let collectionView = collectionView else { return }
contentView.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .white
setupCollectionViewLayout(collectionView)
}
}
private func setupCollectionViewLayout(_ collectionView: UICollectionView) {
NSLayoutConstraint.activate([
collectionView.leadingAnchor
.constraint(equalTo: contentView.leadingAnchor),
collectionView.trailingAnchor
.constraint(equalTo: contentView.trailingAnchor),
collectionView.topAnchor
.constraint(equalTo: contentView.topAnchor),
collectionView.bottomAnchor
.constraint(equalTo: contentView.bottomAnchor),
])
}
}
class CollectionViewCell: UICollectionViewCell {}
class ViewController: UIViewController {
private var lastSelectedCollectionViewCell: CollectionViewCell?
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(tableView)
setupTableViewLayout(tableView)
}
private func setupTableViewLayout(_ tableView: UITableView) {
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "cell",
for: indexPath) as! TableViewCell
guard cell.collectionView == nil else { return cell }
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: UICollectionViewFlowLayout())
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "cell")
cell.collectionView = collectionView
return cell
}
}
extension ViewController: UITableViewDelegate {}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = .gray
return cell
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
lastSelectedCollectionViewCell?.backgroundColor = .gray
if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell {
cell.backgroundColor = .yellow
lastSelectedCollectionViewCell = cell
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 20, height: 20)
}
}
PlaygroundPage.current.liveView = ViewController()
For some reasons I cannot properly display some items from a collection inside an tableview cell when using Xcode 10 beta. I tried all I know for the last 4 days.
I made a small project sample to see what my issue is.
Full code is here if someone wants to run it locally: https://github.com/adrianstanciu24/CollectionViewInsideUITableViewCell
I first add an table view with 2 different resizable cells, first cell has the collection view and a label:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "collCell") as! CollectionTableViewCell
cell.collectionView.collectionViewLayout.invalidateLayout()
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "normalCell")!
return cell
}
}
}
Here is the cell with collection view defined. This also has a height constraint which I updated in layoutSubviews:
class CollectionTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
override func layoutSubviews() {
super.layoutSubviews()
collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "taskCell", for: indexPath as IndexPath) as! TaskCollectionViewCell
cell.name.text = "Task_" + String(indexPath.row)
return cell
}
}
Below is a screenshot with the collection view constraint and how the storyboard looks:
And this is how it looks when running:
The cells are squashed and label on top disappears. What I want is the collection view should grow to show all elements and also making table view cell to resize, but that is not happening at the moment and I can't figure out where the issue is.
If you want the following output:
Code
ViewController:
class ViewController: UIViewController {
let list = [String](repeating: "Label", count: 10)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
tableView.reloadData()
}
public lazy var tableView: UITableView = { [unowned self] in
let v = UITableView.init(frame: .zero)
v.delegate = self
v.dataSource = self
v.estimatedRowHeight = 44
v.rowHeight = UITableViewAutomaticDimension
v.register(TableCell.self, forCellReuseIdentifier: "TableCell")
return v
}()
}
extension ViewController: UITableViewDelegate{
}
extension ViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
cell.label.text = "\(list[indexPath.row]) \(indexPath.row)"
return cell
}
}
TableCell:
class TableCell: UITableViewCell{
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
func commonInit(){
contentView.addSubview(label)
contentView.addSubview(collectionView)
updateConstraints()
}
override func updateConstraints() {
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: topAnchor),
label.leadingAnchor.constraint(equalTo: leadingAnchor),
label.trailingAnchor.constraint(equalTo: trailingAnchor)
])
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: label.bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
])
super.updateConstraints()
}
let list = [String](repeating: "Task_", count: 10)
public let label: UILabel = {
let v = UILabel()
v.textAlignment = .center
return v
}()
public lazy var collectionView: UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
v.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")
v.delegate = self
v.dataSource = self
v.isScrollEnabled = false
return v
}()
override func sizeThatFits(_ size: CGSize) -> CGSize {
let collectionCellHeight = 50
let rows = list.count / 5 // 5: items per row
let labelHeight = 20 // you can calculate String height
let height = CGFloat((collectionCellHeight * rows) + labelHeight)
let width = contentView.frame.size.width
return CGSize(width: width, height: height)
}
}
extension TableCell: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
cell.label.text = "\(list[indexPath.item])\(indexPath.item)"
return cell
}
}
extension TableCell: UICollectionViewDelegate{
}
extension TableCell: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/5, height: 50)
}
}
CollectionCell
class CollectionCell: UICollectionViewCell{
let padding: CGFloat = 5
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(){
backgroundColor = .yellow
contentView.addSubview(label)
updateConstraints()
}
override func updateConstraints() {
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: topAnchor, constant: padding),
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding),
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding),
label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding)
])
super.updateConstraints()
}
public let label: UILabel = {
let v = UILabel()
v.textColor = .darkText
v.minimumScaleFactor = 0.5
v.numberOfLines = 1
return v
}()
}
Made with Swift 5.3 and tested on iOS 14, the follow it should work just copy and paste 😉:
TableViewController.swift
import UIKit
import SnapKit
class TableViewController: UIViewController {
private let tableView: UITableView = UITableView()
private let tableViewCellId = "TableViewCell"
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
// MARK: - Setup UIs
extension TableViewController {
private func setupUI() {
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: tableViewCellId)
view.addSubview(tableView)
tableView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
}
// MARK: - Delegate & DataSource
extension TableViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellId) as! TableViewCell
cell.backgroundColor = .white
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
TableViewCell.swift
import UIKit
import SnapKit
class TableViewCell: UITableViewCell {
private let list = [String](repeating: "Row ", count: 10)
private let collectionViewLayout = UICollectionViewFlowLayout()
lazy private var collectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func layoutSubviews() {
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - UI Setup
extension TableViewCell {
private func setupUI() {
// layout.minimumLineSpacing = 5
// layout.minimumInteritemSpacing = 5
collectionViewLayout.scrollDirection = .horizontal
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionCell")
collectionView.delegate = self
collectionView.dataSource = self
addSubview(collectionView)
collectionView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
}
extension TableViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
cell.titleLabel.text = "\(list[indexPath.item])\(indexPath.item)"
return cell
}
}
extension TableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width / 5, height: 100)
}
}
CollectionViewCell.swift
import UIKit
class CollectionViewCell: UICollectionViewCell {
var titleLabel: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
setupUI()
}
}
// MARK: - UI Setup
extension CollectionViewCell {
private func setupUI() {
titleLabel.font = UIFont(name: "HelveticaNeue", size: 20)
titleLabel.textColor = .white
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.backgroundColor = .systemGreen
titleLabel.textAlignment = .center
addSubview(titleLabel)
titleLabel.snp.makeConstraints {
$0.centerX.centerY.equalToSuperview()
$0.height.equalTo(60)
$0.width.equalTo(150)
}
}
}
If your desired output is following
Then replace your code of collectionview with this
class CollectionTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
var arrForString:[String] = ["Task_0","Task_1","Task_3","Task_4","Task_5","Task_6","Task_7","Task_8","Task_9","Task_10"]
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrForString.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "taskCell", for: indexPath as IndexPath) as! TaskCollectionViewCell
cell.name.text = arrForString[indexPath.row]
cell.layoutIfNeeded()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//we are just measuring height so we add a padding constant to give the label some room to breathe!
var padding: CGFloat = 10.0
var height = 10.0
height = Double(estimateFrameForText(text: arrForString[indexPath.row]).height + padding)
return CGSize(width: 50, height: height)
}
private func estimateFrameForText(text: String) -> CGRect {
//we make the height arbitrarily large so we don't undershoot height in calculation
let height: CGFloat = 120
let size = CGSize(width: 50, height: height)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light)]
return NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil)
}
}
feel free to ask.
In Xcode 8.2.1 and Swift 3 I have a UICollectionView inside a UITableViewCell but I can't get the layout right. basically I want to be able to see all of the star. I can adjust the size of the star but I want to fix the underlying problem, expanding the blue band.
Here is a shot of the view The red band is contentView and the blue band is collectionView. At first glance it looks like collectionView height is the problem but it is actually being hidden by something else. I can't find or change whatever it is hiding the collectionView cell.
I am not using the storyboard beyond a view controller embedded in a navigator.
Here's all the relevant code.
class WishListsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let tableCellId = "WishListsCell"
let collectionCellId = "WishListsCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .white
tableView.register(WishListsCell.self, forCellReuseIdentifier: tableCellId)
self.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
func numberOfSections(in tableView: UITableView) -> Int {
return wishLists.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: tableCellId, for: indexPath) as! WishListsCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView,willDisplay cell: UITableViewCell,forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? WishListsCell else { return }
//here setting the uitableview cell contains collectionview delgate conform to viewcontroller
tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forSection: indexPath.section)
tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
}
func tableView(_ tableView: UITableView,didEndDisplaying cell: UITableViewCell,forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? WishListsCell else { return }
storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
}
}
extension WishListsViewController: UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellId, for: indexPath) as! WishListsCollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
}
class WishListsCell: UITableViewCell {
private var collectionView: UICollectionView!
let cellId = "WishListsCollectionViewCell"
var collectionViewOffset: CGFloat {
get { return collectionView.contentOffset.x }
set { collectionView.contentOffset.x = newValue }
}
func setCollectionViewDataSourceDelegate<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(dataSourceDelegate: D, forSection section : Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = section
collectionView.reloadData()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: contentView.frame, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .blue
collectionView.register(WishListsCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
contentView.backgroundColor = .red
self.contentView.addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class WishListsCollectionViewCell: UICollectionViewCell {
var imageView: UIImageView
override init(frame: CGRect) {
imageView = UIImageView()
super.init(frame: frame)
contentView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
contentView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = .white
NSLayoutConstraint.activate([
NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal,
toItem: contentView, attribute: .width,
multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal,
toItem: contentView, attribute: .height,
multiplier: 1.0, constant: 0.0),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
You can Use View Debugging
Run the project, go back to Xcode and click on the Debug View Hierarchy button in the Debug bar. Alternatively, go to Debug\View Debugging\Capture View Hierarchy.
Now you can select your red view and Xcode will indicate which view is selected.
For more info. Check out: View Debugging in Xcode
Specifically, the problem was the collection view frame had not been properly set. This was only revealed by the great tip that I didn't know about in the accepted answer.
This fixed it:
self.collectionView.frame = CGRect(0, 0, screenWidth, (screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO)