How to create dynamic TableView footer by changing height of cells - swift

I want to create a footer which is dynamic to the height of the tableview cells.
My initial situation looks like:
If I click on a row, it change the height of this cell to 194 (44 before)
It don't show all rows.
If I get the footer -150 it looks like:
And if I close all cells it looks like and the 150 which I get to footer with -150 are white here:
My code:
var selectedCellIndexPath: Int?
let selectedCellHeight: CGFloat = 194.0
let unselectedCellHeight: CGFloat = 44.0
var cellsHeight = [44, 44, 44]
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.beginUpdates()
if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath.row {
selectedCellIndexPath = nil
}
else {
selectedCellIndexPath = indexPath.row
}
if selectedCellIndexPath != nil {
tableView.scrollToRow(at: indexPath, at: .none, animated: true)
}
tableView.endUpdates()
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let rowHeight:CGFloat = 44
var rowsHeight:CGFloat = 3 * rowHeight
/*for i in 0..<cellsHeight.count {
rowsHeight += CGFloat(cellsHeight[i])
}*/
let topHeight = UIApplication.shared.statusBarFrame.height + self.navigationController!.navigationBar.frame.height
let viewHeight = self.view.frame.height
let headerHeight:CGFloat = 30
let height = viewHeight - topHeight - rowsHeight - headerHeight //- 150
return CGFloat(height)
}
Only one row will have the height 194 and the other 44. Any ideas how to solve the problem?
Thx
Edit:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dateFormatter = DateFormatter()
//dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutDateCell", for: indexPath) as! WorkoutDateTableViewCell
cell.typeLabel.text = "Beginn"
cell.dateDatepicker.date = Date()
cell.dateDatepicker.tag = indexPath.row
cell.dateLabel.text = dateFormatter.string(from: cell.dateDatepicker.date)
cell.selectionStyle = .none
return cell
}
else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutDateCell", for: indexPath) as! WorkoutDateTableViewCell
cell.typeLabel.text = "Ende"
cell.dateDatepicker.date = Date()
cell.dateDatepicker.tag = indexPath.row
cell.dateLabel.text = dateFormatter.string(from: cell.dateDatepicker.date)
cell.selectionStyle = .none
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "workoutSportsCell", for: indexPath) as! WorkoutSportsTableViewCell
cell.sportsLabel.text = "Sportart"
cell.sportstypeLabel.text = workoutSports[coreData.getSportsIndex()]
cell.sportsPicker.delegate = self
cell.sportsPicker.dataSource = self
cell.sportsPicker.selectRow(coreData.getSportsIndex(), inComponent: 0, animated: false)
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if selectedCellIndexPath == indexPath.row {
return selectedCellHeight
}
return unselectedCellHeight
}

To archive this you can use only cells instead of footer view.
Step 1: Remove Footer View.
Step 2: Add Cell of Date Picker.
Step 3: When you click on Begin & End DateTime cell, then insert DateTime cell below selected cell and reload table view.
Step 4: Hope that will resolve your problem.
Let me know if you have any query.
Edit: As per discuss you only need to remove the extra cell separator by using tableFooterViewForSection.
So you only need to add below line to solve your problem:
tableView.tableFooterView = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.width, heigth:0))
And Remove func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat method.
Hope it will help you.

Related

I have multiple section , each cell has a button how to know indexpath.row and indexpath.section if user clicks a button [duplicate]

This question already has answers here:
Issue Detecting Button cellForRowAt
(3 answers)
Closed 2 years ago.
Using this code i only get tag which has indexpath.row how to make a button event from it.
TaskPlayButton is my button on that i am passing indexpath.row
for single section this would have worked by now how to do on multiple section.
Is there any other way of knowing which button is clicked?
func numberOfSections(in tableView: UITableView) -> Int {
return mobileBrand.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mobileBrand[section].modelName?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
cell.TaskName.text = mobileBrand[indexPath.section].modelName?[indexPath.row]
cell.TaskPlayButton.tag = indexPath.row
cell.TaskPlayButton.addTarget(self, action: #selector(PlayBtnClicked( _:)), for: UIButton.Event.touchUpInside)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40))
view.backgroundColor = UIColor.rgb(red: 245, green: 245, blue: 245)
let lbl = UILabel(frame: CGRect(x: 15, y: 0, width: view.frame.width - 15, height: 40))
lbl.font = UIFont.systemFont(ofSize: 20)
lbl.text = mobileBrand[section].brandName
view.addSubview(lbl)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if selectedIndex == indexPath.row && isCollapse == true && selectedSection == indexPath.section{
return 240
}else{
return 60
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if selectedIndex == indexPath.row && selectedSection == indexPath.section{
if self.isCollapse == false
{
self.isCollapse = true
}else{
self.isCollapse = false
}
}else{
self.isCollapse = true
}
self.selectedIndex = indexPath.row
self.selectedSection = indexPath.section
TaskTableView.beginUpdates()
TaskTableView.endUpdates()
}
#objc func PlayBtnClicked(_ sender : UIButton)
{
print(sender.tag)
}
you can use another method like pass tag to button like this
cell.button.tag = (indexpath.section * 1000) + indexpath.row
now on your button action you can get like
let row = sender.tag%1000
let section = sender/1000
you can use closure, please look to my codes :
class YourTableViewCell: UITableViewCell {
var button: UIButton!
var buttonAction: ((UIButton) -> Void)?
#objc func buttonPressed(_ sender : UIButton)) {
self.buttonAction?(sender)
}
}
Implement it to your table view delegate :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
cell.TaskName.text = mobileBrand[indexPath.section].modelName?[indexPath.row]
cell.TaskPlayButton.tag = indexPath.row
cell.buttonAction = { sender in
// do your action
// in here, you can get indexPath.row and indexPath.section
}
cell.TaskPlayButton.addTarget(self, action: #selector(PlayBtnClicked( _:)), for: UIButton.Event.touchUpInside)
return cell
}
Hope this answer can help you :)
Pass indexPath to cell, when click the button in this cell, you could get the current indexPath
Custom a button hold a property: indexPath. Pass indexPath to the button in the method cellForRowAt. When you click the button, you could use button.indexPath to get what you want.
I just give you quick tip. It just help you on all table view in your project.
You can follow my answer here - https://stackoverflow.com/a/62481414/8135121
Here it's for you.
You can grab it by position of your button.
I explain it to you.
Make a common table view extension on your class. Just use this.
extension UITableView {
func getCellFrom(sender : UIView,completion : #escaping (UITableViewCell,IndexPath)->()){
var superview = sender.superview
while let view = superview, !(view is UITableViewCell) {
superview = view.superview
}
guard let cell = superview as? UITableViewCell else {
return
}
guard let indexPath = self.indexPath(for: cell) else {
return
}
completion(cell,indexPath)
}
}
Set target from cell in your cell for row at IndexPath function.
cell.TaskPlayButton.addTarget(self, action: #selector(PlayBtnClicked( _:)), for: UIButton.Event.touchUpInside)
Call this in PlayBtnClicked action method.
tableView.getCellFrom(sender: sender) { [weak self] (cell, indexPath) in
// Just use indexPath in here
//This closure return your cell and your button's indexPath also
}

iam begineeer to the swift.i have created the table view when xml parsing is done .its showing me only height of the cell.blank cells

I am new to the Swift language and just a beginner, I have created tableview. I want to show the data whereas when I'm running the code it shows me empty cells. I have checked the delegates and connections .
func numberOfSections(in dashboardtable: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 114
}
func tableView(_ dashboardtable: UITableView, numberOfRowsInSection section: Int) -> Int {
return toddler.count
}
func tableView(_ dashboardtable: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = dashboardtable.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DashTableViewCell
cell.cname.text = toddler[indexPath.row]["ChildName"] as? String
cell.cage.text = toddler[indexPath.row]["Age"] as? String
cell.childc.text = toddler[indexPath.row]["Class"] as? String
if let base64 = toddler[indexPath.row]["Photo"] as? String,let data = Data.init(base64Encoded: base64), let image = UIImage.init(data: data){
cell.childimage.image = image
} else {
cell.childimage.image = UIImage.init(named: "")
}
cell.backgroundColor = UIColor.white
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
cell.clipsToBounds = true
//to display the whole details
print(indexPath.row)
return cell
}
If you want hide lines in blank tableView
use this:
tableView.separatorStyle = .none
be sure set delegate and datasource and call reloadData

UITableView not remembering selection when collapsing

I have a tableview with 3 collapsible sections. users can only select rows in section 3 and when they select it goes green. However, when this section is collapsed all the selections are forgotten and when I re-open the section, usually the first row is always green (though it shouldn't be). Sometimes, other sections end up being green too when they shouldn't - not sure what I've got wrong?
// Number of table sections
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
// Set the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.expandedSectionHeaderNumber == section) {
// If markscheme, create the markscheme format
if (section == 2)
{
return self.markschemeRows.count
}
else
{
let arrayOfItems = self.sectionItems[section] as! NSArray
return arrayOfItems.count
}
} else {
return 0;
}
}
// Set titles for sections
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (self.sectionNames.count != 0) {
return self.sectionNames[section] as? String
}
return ""
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44.0;
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
return 0;
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//recast your view as a UITableViewHeaderFooterView
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor.darkGray
header.textLabel?.textColor = UIColor.white
if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
viewWithTag.removeFromSuperview()
}
let headerFrame = self.view.frame.size
let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
theImageView.image = UIImage(named: "Chevron-Dn-Wht")
theImageView.tag = kHeaderSectionTag + section
header.addSubview(theImageView)
// make headers touchable
header.tag = section
let headerTapGesture = UITapGestureRecognizer()
headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
header.addGestureRecognizer(headerTapGesture)
}
// Load the table data
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
let section = self.sectionItems[indexPath.section] as! NSArray
cell.textLabel?.textColor = UIColor.black
cell.selectionStyle = .none
//cell.backgroundColor = .white
// Get the data from different arrays depending on the section
if indexPath.section == 2 {
cell.textData?.text = markschemeRows[indexPath.row]
} else {
cell.textData?.text = section[indexPath.row] as! String
}
return cell
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0{
if indexPath.row == 0{
return nil
}
}
else if indexPath.section == 1{
if indexPath.row == 0{
return nil
}
}
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .green
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if (cell?.backgroundColor == .green)
{
cell?.backgroundColor = .white
}
}
// MARK: - Expand / Collapse Methods
#objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
let headerView = sender.view as! UITableViewHeaderFooterView
let section = headerView.tag
let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView
if (self.expandedSectionHeaderNumber == -1) {
self.expandedSectionHeaderNumber = section
tableViewExpandSection(section, imageView: eImageView!)
} else {
if (self.expandedSectionHeaderNumber == section) {
tableViewCollapeSection(section, imageView: eImageView!)
} else {
let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
tableViewExpandSection(section, imageView: eImageView!)
}
}
}
func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
let sectionData = self.sectionItems[section] as! NSArray
self.expandedSectionHeaderNumber = -1;
if (sectionData.count == 0) {
return;
} else {
UIView.animate(withDuration: 0.4, animations: {
imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
})
var indexesPath = [IndexPath]()
// If markscheme, different number needed
if (section == 2)
{
for i in 0 ..< markschemeRows.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
else
{
for i in 0 ..< sectionData.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
self.tableView!.beginUpdates()
self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
self.tableView!.endUpdates()
}
}
func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
let sectionData = self.sectionItems[section] as! NSArray
if (sectionData.count == 0) {
self.expandedSectionHeaderNumber = -1;
return;
} else {
UIView.animate(withDuration: 0.4, animations: {
imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
})
var indexesPath = [IndexPath]()
// If markscheme, create the markscheme format
if (section == 2)
{
for i in 0 ..< markschemeRows.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
else
{
for i in 0 ..< sectionData.count {
let index = IndexPath(row: i, section: section)
indexesPath.append(index)
}
}
self.expandedSectionHeaderNumber = section
self.tableView!.beginUpdates()
self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
self.tableView!.endUpdates()
}
}
The key thing to understand here is that the Cells are Reused when you say
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
dequeueReusableCell basically reuses a previously loaded UITableViewCell and in your case you changed the background color of the cell to green
To get a better understanding of the concept consider reading some articles like this one on Reusing Cells
Changes in Code
What you should do considering the above in mind
var backgroundColors = [UIColor](repeating: UIColor.white, count: 10)
you have to save the state of the colors in a model (ideally you should make a custom struct)
now in cellForRowAt add this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
.
.
cell.backgroundColor = backgroundColors[indexPath.row]
// **EDIT**
let cellShouldBeSelected = backgroundColors[indexPath.row] == .green
if cellShouldBeSelected {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
.
.
return cell
}
And your didSelectRowAt and didDeselectRowAt should update the model
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.backgroundColors[indexPath.row] = .green
tableView.reloadRows(at: [indexPath], with: .none)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (self.backgroundColors[indexPath.row] == .green) {
self.backgroundColors[indexPath.row] = .white
tableView.reloadRows(at: [indexPath], with: .none)
}
}
On second thought
Solution 2 (Recommended)
From you comments, i see you only need one selected cell at one time, assuming that keeping an array of backgroundColors is just a bad idea.
declare a int for the selected index
// -1 representing nothing is selected in the beginning
var selectedRow = -1
now your cellForRowAt will look like
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
.
.
if indexPath.section == 2, indexPath.row == self.selectedRow {
cell.backgroundColor = .green
} else {
cell.backgroundColor = .white
}
.
.
return cell
}
And your didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 {
self.selectedRow = indexPath.row
tableView.reloadSections([2], with: .automatic)
}
}
And now you can remove didDeselectRowAt completely

how to tap in content view in didselectrow method in tableview in swift

I am new in ios I am making a project using table view in which I have expanded the table view cell which has 4 Content view.When the table is loaded only first content view show and when I select the row then all content view expands. But I also want that after expanding the all content view cell when I tap on fourth content view then I want to access the indexPath.row in the tapGESTUREAction method of the fourth view.
this my code of expanding Cell which consists of 4 content view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(YearArr.count)
return YearArr.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
cell.selectionStyle = .none
cell.lblGrossSal.text = EarnArr[indexPath.row]
cell.lblTotlSal.text = netPayArr[indexPath.row]
cell.lblmonthhName.text = YearArr[indexPath.row]
print(selectedIndex,indexPath.row)
let height = cell.bounds.height
print(height)
return cell;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
cell.selectionStyle = .none
if(selectedIndex == indexPath.row) {
return 190;
return self.calculateHeight(selectedIndexPath: indexPath)
} else {
return 50;
}
}
// fourthView
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(selectedIndex == indexPath.row) {
selectedIndex = -1
} else {
selectedIndex = indexPath.row
}
self.expandTableView.beginUpdates()
//self.expandTableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic )
self.expandTableView.endUpdates()
}
func calculateHeight(selectedIndexPath: IndexPath) -> CGFloat {
let cell = self.expandTableView.cellForRow(at: selectedIndexPath) as! customCell
cell.lblDeductSal.frame = self.cellSummaryLabelFrame(cell: cell, selectedIndexPath: selectedIndexPath)
return 80 + 35 + 21 + 10 + cell.lblDeductSal.frame.size.height + 30
}
func cellSummaryLabelFrame(cell: customCell, selectedIndexPath: IndexPath) -> CGRect {
print(DeductionArr[selectedIndexPath.row])
cell.lblDeductSal.text = DeductionArr[selectedIndexPath.row]
cell.lblDeductSal.numberOfLines = 0
var labelFrame = cell.lblDeductSal.frame
let maxSize = CGSize.init(width: cell.lblDeductSal.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
let requiredSize = cell.lblDeductSal.sizeThatFits(maxSize)
labelFrame.size.height = requiredSize.height
return labelFrame
}
In heightForRowAt indexPath, you are using two return. The first one will execute. The calculated height method can't execute. And there is no need of tableView.dequeueReusableCell. That function only need the height of cell.
Example:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if(selectedIndex == indexPath.row) {
return self.calculateHeight(selectedIndexPath: indexPath)
} else {
return 50;
}
}
And You can also use dynamic cell height, In your viewDidLoad:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44 //Default cell height
And here NO NEED OF heightForRowAt indexPath method. The height will automatically calculate.

UITableViewController insert different cells into different sections

I have a TableViewController with 3 sections with their own headers.
Now I want before inserting any cell, check a property and then add the cell into different sections.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "TasksTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TasksTableViewCell else {
fatalError("The dequeued cell is not an instance of TasksTableViewCell.")
}
// Fetches the appropriate task for the data source layout.
let task = tasks[indexPath.row]
cell.nameLabel.text = task.name
cell.photoImageView.image = task.photo
cell.timeControl.text = task.lengthDisplay.replacingOccurrences(of: "Length: ", with: "")
if(task.importanceLevel == 0){
// add cell to section 0
}
else if(task.importanceLevel == 1){
// add cell to section 1
}
// Configure the cell...
return cell
}
Can u see the comment, is there any way to do that?
Thank you very much
You can create a model and pass empty count arrays at first for each section and row in data source methods.
And then initialize the count and fill arrays their then reload your table view.
I hope you know there is numberOfSections method too.
I think this code will help you:
let arr = [5,2,7,10,2]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 5
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arr[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("celldata", forIndexPath: indexPath)
cell.textLabel?.text = "section \(indexPath.section)"
cell.detailTextLabel?.text = "Rows \(indexPath.row)"
return cell
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.width, height: 20))
let lbl = UILabel(frame: CGRect(x: 5, y: 5, width: self.tableView.frame.width, height: 15))
lbl.text = "\(section)"
view.backgroundColor = UIColor.grayColor()
view.addSubview(lbl)
return view
}
You can try it like this
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.section == 0){
let cellIdentifier = "TasksTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TasksTableViewCell else {
fatalError("The dequeued cell is not an instance of TasksTableViewCell.")
}
// Fetches the appropriate task for the data source layout.
let task = tasks[indexPath.row]
cell.nameLabel.text = task.name
cell.photoImageView.image = task.photo
cell.timeControl.text = task.lengthDisplay.replacingOccurrences(of: "Length: ", with: "")
return cell
}
else if(indexPath.section == 1)
let cellIdentifier = "TasksTableViewCell1"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TasksTableViewCell1 else {
fatalError("The dequeued cell is not an instance of TasksTableViewCell.")
}
// Fetches the appropriate task for the data source layout.
let task = tasks[indexPath.row]
cell.nameLabel.text = task.name
cell.photoImageView.image = task.photo
cell.timeControl.text = task.lengthDisplay.replacingOccurrences(of: "Length: ", with: "")
return cell
}
}