Multiple Sections In UITableView Swift 4 - swift

Well, I am trying to make a registration form. My problem is that in the section cell doesn't show the correct info into the sections, it shows all the info in the sections... ermm I think something I missed on the cell for row.
So, my code would look something like this.
UITableViewDataSource
extension IEKRegistrationPage3Controller: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "IEKRegistrationPage3GraduateCell", for: indexPath) as! IEKRegistrationPage3GraduateCell
// Graduate
if let graduate = Graduate(rawValue: indexPath.row) {
cell.updateLayout(withTitle: graduate.description, isSelected: [graduate] == iekRegistrationFormData.graduate)
}
if let student = Student.init(rawValue: indexPath.row) {
cell.updateLayout(withTitle: student.description, isSelected: [student] == iekRegistrationFormData.student)
}
return cell
}
}
Also here is the UITableViewDelegate
extension IEKRegistrationPage3Controller: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Graduate
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
if let graduate = Graduate(rawValue: indexPath.row) {
iekRegistrationFormData.graduate = [graduate]
}
}
// Student
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 {
if let student = Student(rawValue: indexPath.row) {
iekRegistrationFormData.student = [student]
}
}
// Engilsh
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 2 {
// TODO
}
tableView.reloadData()
}
}
and finally the titleForHeaderInSection
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// Graduate
if section == 0 {
return "ΑΠΟΦΟΙΤΟΣ"
}
// Student
if section == 1 {
return "ΦΟΙΤΗΤΗΣ"
}
// Engilsh
if section == 2 {
return "ΑΓΓΛΙΚΑ"
}
return nil
}

Related

SWIFT / UIKit Footer text displaying over dynamic tableViewCell

I have a UITableViewcontroller setup with just two cells. The footer text is displaying over the last cell.
Strangely I have other controllers with practically the same setup and code and where the footer is showing as expected.
I have tried tried changing the style group / inset etc.
Any ideas appreciated. Thanks
import UIKit
class LanguagesTableViewController: UITableViewController {
var checked = [Bool]()
var choices = ["English","French"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsMultipleSelection = false
let defaults = UserDefaults.standard
checked = defaults.array(forKey: "Language") as? [Bool] ?? [true, false]
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateSwitchState()
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "languageChoiceCell", for: indexPath)
cell.textLabel?.text = choices[indexPath.row]
if !checked[indexPath.row] {
cell.accessoryType = .none
} else if checked[indexPath.row] {
cell.accessoryType = .checkmark
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return choices.count
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if checked[indexPath.row] {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableView.ScrollPosition.none)
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return Constants.languagesFooterText
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// If we are selecting a row that is already checked we do nothing
guard !checked[indexPath.row] else { return }
// Reset all checked state.
checked = [Bool](repeating: false, count: choices.count)
// And set the current row to true.
checked[indexPath.row] = true
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
checked[indexPath.row] = false
} else {
cell.accessoryType = .checkmark
checked[indexPath.row] = true
}
}
updateSwitchState()
}
// did ** DE ** Select
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
checked[indexPath.row] = false
} else {
cell.accessoryType = .checkmark
checked[indexPath.row] = true
}
}
updateSwitchState()
}
func updateSwitchState() {
let defaults = UserDefaults.standard
defaults.set(checked, forKey: "Language")
}
}
You should set a height on your footer view. You can do this by calling tableView(:heightForFooterInSection:) and returning UITableView.automaticDimension.
As you are inheriting from UITableViewController you can do it in the following way
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
UITableView.automaticDimension
}
This will give you the following result:

TableView action per item

I have a tableView like this:
class ViewController: UIViewController {
#IBOutlet var tableView: UITableView!
let names = ["TEXT1", "TEXT2", "TEXT3"]
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
}
}
extension ViewControllerMeer: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let name = names[indexPath.row]
print("You clicked on \(name)")
}
}
extension ViewControllerMeer: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
let n = names[indexPath.item]
switch n {
case "TEXT1":
print("s1")
case "TEXT2":
print("s2")
case "TEXT3":
print("s3")
default:
break
}
return cell
}
}
It reads the items from the 'let names', So far so good :) I now want to add some actions because now every item will print 'You tapped me'. I figured something out like
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
print("cell1")
} else if indexPath.row == 1 {
print("cell2")
} else if indexPath.row == 2 {
print("cell3")
}
}
The only problem is that it generates an error 'Method does not override any method from its superclass'. So I guess this won't work. What would be a good method to do it?
remove the override in front of func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
And you can either to a big if statement or switch statement to do something with the names or you can do something like:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let name = names[indexPath.row]
print("You clicked on \(name)")
switch indexPath.row {
case 0:
//do something
self.shareApp()
case 1:
//do something else
self.writeReview()
default:
break
}
}
I just copied your codes to show you basically if you really want to override tableview functions
class ViewController: UITableViewController {
#IBOutlet var tableView: UITableView!
let names = ["TEXT1", "TEXT2", "TEXT3"]
override func viewDidLoad() {
super.viewDidLoad()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped me!")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let name = names[indexPath.row]
print("You clicked on \(name)")
}
}

How do I create two different sections on table?

I am trying to separate these data into two different sections :
–one section with movies of runtime more than 120 mins, another for the rest.
The problem is I am pulling data from the same array. How can I apply conditional statement/logic and insert into each section depending on the value? I am able to pull data from the different arrays and insert into the different sections however. Please guide me. Thank you
import UIKit
class ViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
return movieList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : MovieCell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell
let p = movieList[indexPath.row]
cell.nameLabel.text = p.movieName
cell.runTimeLabel.text = "\(p.runtime) mins"
cell.movieImageView.image = UIImage(named: p.imageName)
return cell
}
var movieList : [Movie] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
movieList.append(Movie(movieName:"Oklahoma Crude",
movieDesc:"",
runtime:115,
imageName:"movie_oklahoma"))
movieList.append(Movie(movieName:"Bootleggers",
movieDesc:"",
runtime:140,
imageName:"movie_bootleggers"))
movieList.append(Movie(movieName:"Superdad",
movieDesc:"",
runtime:112,
imageName:"movie_superdad"))
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
movieList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
#IBAction func editButton(_ sender: Any) {
if !self.tableView.isEditing
{
(sender as AnyObject).setTitle("Done", for: .normal)
tableView.setEditing(true, animated: true)
}
else
{
(sender as AnyObject).setTitle("Edit", for: .normal)
tableView.setEditing(false, animated: true)
} }
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let m = movieList[sourceIndexPath.row]
movieList.remove(at:sourceIndexPath.row)
movieList.insert(m, at:destinationIndexPath.row)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
let headerTitles = ["More than 120 minutes", "Others"]
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < headerTitles.count {
return headerTitles[section]
}
return nil
}
}
Suppose with 120 will be section = 0
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
let arr120 = movieList.filter { $0.runtime >= 120 }
let arrLess120 = movieList.filter { $0.runtime < 120 }
return section == 0 ? arr120.count : arrLess120.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let arr120 = movieList.filter { $0.runtime >= 120 }
///..
}
else {
let arrLess120 = movieList.filter { $0.runtime < 120 }
////....
}
Howver this not the perfest solution , you can organize your data source to
struct AllMovies {
let title:String // ex. above 120
let arr:[Movie]
}
It is better to have 2 arrays - one containing the movies shorter than 120mins and one containing the movies longer than 120mins. You should create those two arrays from the movieList array:
var lessThan120: [Movie]!
var moreThan120: [Movie]!
override func viewDidLoad() {
super.viewDidLoad()
movieList.append(Movie(movieName:"Oklahoma Crude",
movieDesc:"",
runtime:115,
imageName:"movie_oklahoma"))
movieList.append(Movie(movieName:"Bootleggers",
movieDesc:"",
runtime:140,
imageName:"movie_bootleggers"))
movieList.append(Movie(movieName:"Superdad",
movieDesc:"",
runtime:112,
imageName:"movie_superdad"))
let count = movieList.partition(by: {$0.runtime > 120})
lessThan120 = Array(movieList[0..<count])
moreThan120 = Array(movieList[count...])
}
Then implementing the data source methods would be very simple:
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
if section == 0 {
return moreThan120.count
} else if section == 1 {
return lessThan120.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : MovieCell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell
let p = indexPath.section == 0 ? moreThan120[indexPath.row] : lessThan120[indexPath.row]
cell.nameLabel.text = p.movieName
cell.runTimeLabel.text = "\(p.runtime) mins"
cell.movieImageView.image = UIImage(named: p.imageName)
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
var movieList = [String]()
var movieListGreaterThen120 = [String]()
var movieListSmallerThen120 = [String]()
for item in movieList {
if item.runtime > 120 {
movieListGreaterThen120.append(item)
}else {
movieListSmallerThen120.append(item)
}
}
//MARK: - tableView DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
if section == 0 {
return movieListGreaterThen120.count
}else {
return movieListSmallerThen120.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : MovieCell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell
if indexPath.section == 0 {
//Load your movieListGreaterThen120 Data
}else {
//Load your movieListSmallerThen120 Data
}
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
"movieList" array can be filtered out depending on the runtime value.
if indexPath.section == 0 {
movieList.filter { $0.runtime >= 120 }
}
else {
movieList.filter { $0.runtime < 120 }
}

swift tableview change reloadData to insertRows

trying to change method to update the data, because with reloadData have lag
let oldIns = insertCounter
insertCounter += Int(INSERT_MESSAGES) // +40
var indexPaths = [IndexPath]()
for section in (oldIns..<insertCounter) {
indexPaths.append(IndexPath(row: 2, section: section))
}
tableView.beginUpdates()
tableView.insertRows(at: indexPaths, with: .automatic)
tableView.endUpdates()
but i have error
The number of sections contained in the table view after the update
(80) must be equal to the number of sections contained in the table
view before the update (40), plus or minus the number of sections
inserted or deleted (0 inserted, 0 deleted)
func numberOfSections(in tableView: UITableView) -> Int {
return min(insertCounter, Int(dbmessages.count))
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return RCMessages().sectionHeaderMargin
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return RCMessages().sectionFooterMargin
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.clear
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
view.tintColor = UIColor.clear
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath.row == 0) {
return RCSectionHeaderCell.height(indexPath, messagesView: self)
}
if (indexPath.row == 1) {
return RCBubbleHeaderCell.height(indexPath, messagesView: self)
}
if (indexPath.row == 2) {
let rcmessage = self.rcmessage(indexPath)
if (rcmessage.type == RC_TYPE_STATUS) { return RCStatusCell.height(indexPath, messagesView: self) }
if (rcmessage.type == RC_TYPE_TEXT) { return RCTextMessageCell.height(indexPath, messagesView: self) }
}
if (indexPath.row == 3) {
return RCBubbleFooterCell.height(indexPath, messagesView: self)
}
if (indexPath.row == 4) {
return RCSectionFooterCell.height(indexPath, messagesView: self)
}
return 0
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCSectionHeaderCell", for: indexPath) as! RCSectionHeaderCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (indexPath.row == 1) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCBubbleHeaderCell", for: indexPath) as! RCBubbleHeaderCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (indexPath.row == 2) {
let rcmessage = self.rcmessage(indexPath)
if (rcmessage.type == RC_TYPE_STATUS) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCStatusCell", for: indexPath) as! RCStatusCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (rcmessage.type == RC_TYPE_TEXT) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCTextMessageCell", for: indexPath) as! RCTextMessageCell
cell.bindData(indexPath, messagesView: self)
let numSections = self.tableView.numberOfSections
if numSections == 1 {
updateTableContentInset()
}
return cell
}
}
if (indexPath.row == 3) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCBubbleFooterCell", for: indexPath) as! RCBubbleFooterCell
cell.bindData(indexPath, messagesView: self)
return cell
}
if (indexPath.row == 4) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RCSectionFooterCell", for: indexPath) as! RCSectionFooterCell
cell.bindData(indexPath, messagesView: self)
return cell
}
return UITableViewCell()
}
How can i correct insert new row in tableview?
Before does like this
insertCounter += Int(INSERT_MESSAGES)
tableView.reloadData()
It's a pretty simple code line:
tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .top)
This will insert the new row at the top of the table view. Then you would reload the data. This should fix the problem.

Can't un check all cell before check one swift 2

I m using swift 2 and UITableViews and when I press a cell a checkmark appear, but I wan't that only one cell can be checked in my tableview so the other checkmarks will disappear from my tableview. I tried different technics without success. I have a CustomCell with just a label.
Here is my code :
import UIKit
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var tableView: UITableView!
var answersList: [String] = ["One","Two","Three","Four","Five"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return answersList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomCell", forIndexPath: indexPath) as! MyCustomCell
cell.displayAnswers(answersList[indexPath.row]) // My cell is just a label
return cell
}
// Mark: Table View Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Element selected in one of the array list
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark {
cell.accessoryType = .None
} else {
cell.accessoryType = .Checkmark
}
}
}
}
Assuming you've only section here's what you can do
// checkmarks when tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = indexPath.section
let numberOfRows = tableView.numberOfRowsInSection(section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
cell.accessoryType = row == indexPath.row ? .Checkmark : .None
}
}
}
Fixed code from #SirH to work with Swift 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let section = indexPath.section
let numberOfRows = tableView.numberOfRows(inSection: section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRow(at:IndexPath(row: row, section: section)) {
cell.accessoryType = row == indexPath.row ? .checkmark : .none
}
}
}