I am a new Swift programmer and I am currently working on a very simple to-do-list application. The catch is that I want to display a not-to-do list as well. Additionally, I am attempting to do this all through code.
I want the user to be able to scroll horizontally between 2 CollectionViewCells, that each have a TableView within them displaying a 'To Do List' and a 'Not To Do List'.
So far I have a ViewController that creates a UICollectionView that has 2 custom cells that each fills up the window, so the user can scroll between them.
I am working on the "Not To Do List" cell, and I am trying to display a TableView within it, but I am having difficulty displaying it.
Here is my code:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
...
collectionView.register(ToDoListCell.self, forCellWithReuseIdentifier: toDoListCellid)
collectionView.register(NotToDoListCell.self, forCellWithReuseIdentifier: notToDoListCellid)
...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.item == 0) {
let toDoCell = collectionView.dequeueReusableCell(withReuseIdentifier: toDoListCellid, for: indexPath)
return toDoCell
}
else {
let notToDoCell = collectionView.dequeueReusableCell(withReuseIdentifier: notToDoListCellid, for: indexPath)
return notToDoCell
}
}
class NotToDoListCell: UICollectionViewCell {
var ntdlArray = ["Play Video Games", "Eat out", "Watch Netflix"]
let ntdlCell = "ntdlCell"
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.orange
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension NotToDoListCell: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return ntdlArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ntdlCell, for: indexPath)
cell.textLabel?.text = ntdlArray[indexPath.item]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
I would expect that the table view would show up with 3 rows of text containing: "Play Video Games", "Eat Out", and "Watch Netflix" but all I see is an orange screen (from when I set the background color of the NotToDoListCell to orange). Any help would be greatly appreciated.
Thank you in advance.
To do this completely programmatically without using a nib/xib file , you need to make a table view inside a collectionview cell , you can do something like this:
You need add the
tableView
in yourNotToDoListCell
as outlet from your xib file and add in theawakeFromNib
methodself.tableView.dataSource = self