Xcode - TableView - Multiple sections - ios

I have multiple sections in my TableView and I'm a bit stuck to display there names in the correct section. I'm new to xcode, so this an easy one for most but not for me :s
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return areas.bars.count
} else {
return areas.clubs.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("barsandclubsIdentifier", forIndexPath: indexPath)
if section == 0 { // **This is where I'm stuck I can't put section -> UITableViewCell**
let bars = areas.bars
let bar = bars[indexPath.row]
cell.textLabel?.text = bar.name
return cell
} else {
let clubs = areas.clubs
let club = clubs[indexPath.row]
cell.textLabel?.text = club.name
}
}

Try this may help you :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("barsandclubsIdentifier", forIndexPath: indexPath)
if indexPath.section == 0 { // **This is where I'm stuck I can't put section -> UITableViewCell**
let bars = areas.bars
let bar = bars[indexPath.row]
cell.textLabel?.text = bar.name
}else {
let clubs = areas.clubs
let club = clubs[indexPath.row]
cell.textLabel?.text = club.name
}
return cell
}

Related

Show two different custom cells in same uitableview - swift firebase

I am currently having a problem with displaying two different types of custom cells on the same uitableview.
What I have managed so far, is receiving the "updates" to the update cell, known as cell. I just cannot figure out how to also get numberOfRowsInSection to return two values, so both of my cells will show.
Let me explain through my code:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return updates.count
return updatesTask.count // I CANNOT DO THIS - what can I do instead?
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
let update = updates[indexPath.row]
let updateTask = updatesTask[indexPath.row]
// Example of the two different cells that need different data from firebase
cell.nameLabel.text = update.addedByUser
cellTask.nameLabel.text = updateTask.addedByUser
As you can probably see, the let updateTask is trying to get an indexPath.row but that is not possible, since I cannot have two return values in the numberOfRowsInSection, which is a problem because that number is referring to the place where the data is stored in my firebase database.. How can I modify this to make it work?
Hope you guys understand where I am going with this, otherwise let me know and I will try to explain better :-)
#Callam's answer is great if you want to put them in two sections.
This is the solution if you want all to be in one section.
First, in numberOfRowsInSection method you need to return the sum of those two array counts like this: return (updates.count + updatesTask.count)
Then you need to configure cellForRowAtIndexPath method like this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row < updates.count{
// Updates
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let update = updates[indexPath.row]
cell.nameLabel.text = update.addedByUser
return cell
} else {
// UpdatesTask
let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
let updateTask = updatesTask[indexPath.row-updates.count]
cellTask.nameLabel.text = updateTask.addedByUser
return cellTask
}
}
This will display all cells followed by all cellTasks.
If updates array and updatesTask array have equal number of items and you want to display them one by one you can use this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row % 2 == 0 {
// Updates
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let update = updates[indexPath.row/2]
cell.nameLabel.text = update.addedByUser
return cell
} else {
// UpdatesTask
let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
let updateTask = updatesTask[indexPath.row/2]
cellTask.nameLabel.text = updateTask.addedByUser
return cellTask
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return updates.count
case 1:
return updatesTask.count
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let update = updates[indexPath.row]
cell.nameLabel.text = update.addedByUser
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
let updateTask = updatesTask[indexPath.row]
cell.nameLabel.text = updateTask.addedByUser
return cell
default:
return UITableViewCell()
}
}
For each row you have to choose if you want to display one type of cell or the other but not both. You should have a flag in numberOfRowsInSection telling your method that you want to load Cell or CellTask and then return the correct number of rows.
You should return total number of rows in your numberOfRowsInSection method. so you can return summation of your both array's count something like,
return updates.count + updatesTask.count
now in your cellForRowAtIndexPath method you can differentiate your cell something like,
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
if indexPath.row % 2 == 1 {
//your second cell - configure and return
return cellTask
}
else
{
//your first cell - configured and return
return cell
}
I am not sure what you want to achieve. If you want to display the number of cells updates[] and updatesTask[] have elements you can do it like this
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (updates.count + updatesTask.count)
}
then you can modify your cellForRowAtIndexPath method like this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
if indexPath.row < updates.count{
//update
let update = updates[indexPath.row]
cell.nameLabel.text = update.addedByUser
}else{
let updateTask = updatesTask[indexPath.row]
cellTask.nameLabel.text = updateTask.addedByUser
}
return cell
}
with the if condition you can choose from which array you are taking data.
But be careful to name an array exactly the same as another constant like you did here
let updateTask = updatesTask[indexPath.row]
You can create a simple View Model, that will hold the multiple item types:
enum ViewModelItemType {
case nameAndPicture
case about
case email
case friend
case attribute
}
protocol ViewModelItem {
var type: ViewModelItemType { get }
var rowCount: Int { get }
var sectionTitle: String { get }
}
Then create a model item type for each section. For example:
class ViewModelNameAndPictureItem: ViewModelItem {
var type: ProfileViewModelItemType {
return .nameAndPicture
}
var sectionTitle: String {
return “Main Info”
}
var rowCount: Int {
return 1
}
var pictureUrl: String
var userName: String
init(pictureUrl: String, userName: String) {
self.pictureUrl = pictureUrl
self.userName = userName
}
}
Once you configure all your section items with, you can save them in ViewModel:
class ProfileViewModel {
var items = [ViewModelItem]()
}
And add to you TableViewController:
let viewModel = ViewModel()
In this case, NumberOfSections, NumberOfRows and CellForRowAt methods will be clean and simple:
override func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.items.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.items[section].rowCount
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = viewModel.items[indexPath.section]
switch item.type {
// configure celll for each type
}
}
Configuring the section title will also be very neat:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.items[section].sectionTitle
}
Please check my recent tutorial on this topic, that will answer your question with the details and examples:
https://medium.com/ios-os-x-development/ios-how-to-build-a-table-view-with-multiple-cell-types-2df91a206429

Control multiple tableviews in a single view

I have a table view nested in a collection view and i'm returning 3 (possibly more in the future) collection view cells and I was wondering if it is possible to present different content in each one of the collection cells? I attached a few screenshots to better understand what I am taking about. Thanks.
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = "Homeroom"
cell.detailTextLabel?.text = "8:15 AM - 9:00 AM"
cell.selectionStyle = .None
return cell
}
Yes you can. You need set a property for every tableView you have and in delegate method compare it like below
class Some: UIViewController {
var firstTableView: UITableView
var secondTableView: UITableView
override func viewDidLoad() {
firstTableView = YOUR_FIRST
secondTableView = YOUR_Second
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if tableView == firstTableView {
return 2;
}
else if tableView == secondTableView {
return 1;
}
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if tableView == firstTableView {
return 2;
}
else if tableView == secondTableView {
return 1;
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
if tableView == firstTableView {
cell = tableView.dequeueReusableCellWithIdentifier("cellOfFirstTableView", forIndexPath: indexPath) as! UITableViewCell
}
else if tableView == secondTableView {
cell = tableView.dequeueReusableCellWithIdentifier("cellOfSecondTableView", forIndexPath: indexPath) as! UITableViewCell
}
// Configure the cell...
if tableView == firstTableView {
cell.textLabel?.text = "Homeroom"
cell.detailTextLabel?.text = "8:15 AM - 9:00 AM"
cell.selectionStyle = .None
}
else if tableView == secondTableView {
cell.textLabel?.text = "Homeroom"
cell.detailTextLabel?.text = "8:15 AM - 9:00 AM"
cell.selectionStyle = .None
}
return cell
}
}
You can use UITableViewDelegate / UITableViewDataSource methods with if else conditions or some thing similar
eg.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == table1 { // table1 is a global var for the table
} else if tableView == table2 {
}
}
But I think it will be very clear if you use separate controller class for each table so you can easily manage the code.
But this depends on what type of data you have. If data is completely unrelated you can just use 3 different controllers.
Or if you can reuse data and codes among 3 tables then you can decide if you wanna use 3 different controllers or to use i class with above method.
eg.
let table1Controller = Table1Controller(dataList1)
let table2Controller = Table2Controller(dataList2)
let table3Controller = Table3Controller(dataList3)
table1.delegate = table1Controller
table1.dataSource = table1Controller
table2.delegate = table2Controller
table2.dataSource = table2Controller
table3.delegate = table3Controller
table3.dataSource = table3Controller

How to custom order two different sections in a tableview Swift

I have successfully implemented two different sections in my table view. Section 1 has 3 cells displayed first, then section 2 has 12 displayed afterwards.
I would like to have it ordered so section 1 has its 3 cells mixed into section 2 (12 cells) So in this case it would be displayed every 4 cells. I would like to code it in a way that when the section 2 cells increases over time it keeps section 1 every 4 cells.
Here is the tableview delegate functions I have at the moment
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
if (section == 0) {
return 3 // At the moment I have hard coded it will change it to array.count
} else {
return eventNameArray.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("MovingCell", forIndexPath: indexPath) as! WhatsOnMovingTableViewCell
// Do something!
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! WhatsOnTableViewCell
// Do something!
return cell
}
}
You cannot mix the cells of different sections.
Since that is what you want the solution is to remove the sections all together or include more sections:
Solution 1:
1 Section with x cells: Cell|Cell|Cell|Cell|MovingCell|Cell|Cell|Cell|Cell|Moving Cell
Solution 2: y Sections with 1 or z cells - Cell|Cell|Cell|Cell + MovingCell + Cell|Cell|Cell|Cell + Moving Cell
I will show you the code that would be needed for Solution 1. You will need to have some variable indicating what the length of Cell-semi-sections would be, e.g. let cellCountBeforeMoving = 4:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3 + eventNameArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.item + 1) % (cellCountBeforeMoving + 1) == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("MovingCell", forIndexPath: indexPath) as! WhatsOnMovingTableViewCell
// Do something!
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! WhatsOnTableViewCell
// Do something!
return cell
}
}
Note the indexes are now a little offset and you have to be careful accessing the array. The probably correct way to get the element corresponding to a given indexPath is
eventNameArray[indexPath.item - ((indexPath.item + 1) / (cellCountBeforeMoving + 1))]
Solution 1 will end up something like: (you need some var which gives you the number of interplaced MovingCells)
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return movingCells * 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section % 2 == 1 {
return 1
}
return cellCountBeforeMoving
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section % 2 == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("MovingCell", forIndexPath: indexPath) as! WhatsOnMovingTableViewCell
// Do something!
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! WhatsOnTableViewCell
// Do something!
return cell
}
}

Creating sections with headers with two dynamic tableviewcells in Swift

I have a table view with two cells, "electionInfo" and "candidates". Candidates returns an array of the candidates, while electionInfo gives a single text body (so just one cell). I'd like to divide them into two sections with their respective headers. Right now, it gives me one header for both cells. How do I fix it?
Thanks!!
My code...
#IBOutlet weak var table: UITableView!
var info: [PFObject] = []
var items: [PFObject] = []
let titles = ["Election Info", "Candidates"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count + 1
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titles[section]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == self.items.count {
let cell = table.dequeueReusableCellWithIdentifier("candidateCell") as! CandidateTableViewCell
let candidate = items[indexPath.row]
cell.candidateImage.file = candidate["image"] as! PFFile
cell.candidateImage.loadInBackground()
cell.candidateName?.text = candidate["name"] as! String
cell.candidateParty?.text = candidate["partyAffiliation"] as! String
return cell
} else {
let cell = table.dequeueReusableCellWithIdentifier("electionCell") as! ElectionInfoTableViewCell
cell.electionInfo.text = "hey there"
}
}
}
internal func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2 //or the number of sections you have
}
internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = UITableViewCell()
if indexPath.section == 0 {
let candidateCell = table.dequeueReusableCellWithIdentifier("candidateCell") as! CandidateTableViewCell
let candidate = items[indexPath.row]
cell.candidateImage.file = candidate["image"] as! PFFile
cell.candidateImage.loadInBackground()
cell.candidateName?.text = candidate["name"] as! String
cell.candidateParty?.text = candidate["partyAffiliation"] as! String
return candidateCell
} if indexPath.section == 1 {
let electionCell = table.dequeueReusableCellWithIdentifier("electionCell") as! ElectionInfoTableViewCell
cell.electionInfo.text = "hey there"
return electionCell
}
return cell
}
then you have also to change your numberOfRowsInSection
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return self.items.count
}
if section == 1 {
return self.items.count // or the number of rows you have in that section
}
}
A section and a cell is different thing in tableview. Right now your code gives you section instead of cell because you return self.items.count + 1 in numberOfSectionsInTableView. A fix for this;
Since your tableview should contain two section only you must return 2 or titles.count in numberOfSectionsInTableView
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.titles.count
}
Next return corresponding array count in numberOfRowsInSection
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return self.info.count
}else{
return self.items.count
}
}
And finally in cell for row at index path return cell based on a section:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 1 {
let cell = table.dequeueReusableCellWithIdentifier("candidateCell") as! CandidateTableViewCell
let candidate = items[indexPath.row]
cell.candidateImage.file = candidate["image"] as! PFFile
cell.candidateImage.loadInBackground()
cell.candidateName?.text = candidate["name"] as! String
cell.candidateParty?.text = candidate["partyAffiliation"] as! String
return cell
} else {
let cell = table.dequeueReusableCellWithIdentifier("electionCell") as! ElectionInfoTableViewCell
cell.electionInfo.text = "hey there"
}
}

Display show more in uitableview

By default each section should show maximum three cells. If any cell contains more than three cells, it should display 'show more' option.If show more is tapped I want to display the rest of the cells in that particular section. Two days I spent, nothing worked out.Segments at the top of the table. Depend on segment selected, tableview load the cells. This code for each segment each section varies, so the func cellForRowAtIndexPath: becomes big seriously very big. I roughly added code. This code is what i have tried.
if segmentName == .Feature || segmentName == .Services
{
if indexPath.section == 0
{
if boolShowFullFeature[indexPath.section] == false
{
if indexPath.row == showCells
{
return createShowMoreCell(indexPath.section)
}
else
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SearchListViewCell
var firstTitle = "", secondTitle = "", thirdTitle = "", recomendValue = "", starValue = ""
(firstTitle, secondTitle, thirdTitle, recomendValue, starValue) = model.foodValue[indexPath.row]
cell.configureCell(firstTitle, secondTitle: secondTitle, thirdTitle: thirdTitle, recomendValue: recomendValue, starValue: starValue)
return cell
i had actually done this before. here is sample code:
var objects = [["1","2","3"],["q","w","e","r","t","y"],["z","x","c","v","b","n","m"]]
var sec = ["sec a","sec b","sec c"]
var showallSec = 0
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sec.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let items = objects[section].count
if items > 3{
if section == showallSec-1{
return items
}
return 4
}
return items
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.section][indexPath.row]
cell.textLabel!.text = object
if(indexPath.section != showallSec-1){
if(indexPath.row == 3){
cell.textLabel!.text = "show more"
}}
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sec[section]
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(indexPath.row == 3){
showallSec = indexPath.section + 1
tableView.reloadData()
}
}

Resources