sumit
7/5/2019 - 9:31 AM

tableView

Steps to start Table View

  1. You can get tableview in .storyboard either by using TableViewcontroller or ( drag and drop Table View from object library in normal ViewController, drag Table View cell under Table View.

    • Advantage of TableViewController will be that you don't have to make your Viewcontroller class delegate of UITableViewDataSource
  2. Select Table View Cell in .storyboard -> go to attributes pane -> Rename Identifier to something unique Example "cellReuseIdentifier"

  3. Make tableView IBOutlet named IBOutletTableView

  4. Add below lines in viewDidLoad method

    for i in 0...5{
      data.append("\(i)")
    }
    IBOutletTableView.dataSource = self
    
  5. Make your class delegate of UITableViewDataSource

        class ViewController: UITableViewController {
    
  6. Add below functions in ViewController class

       override func numberOfSections(in tableView: UITableView) -> Int {
         return 2
     }
    
     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         
         return data.count
     }
     
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
         let text = data[indexPath.row]
         cell.textLabel?.text = text
         return cell
     }
     
     override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         return "Section No: \(section)"
     }
    
  7. IMPORTANT: BIG FLAW in TableView. when you slide below in tableview then new cells are not created only the cellForRowAt function is called to change the property of the cell in that position.

  • It can be demonstrated by this function, you will notice as you slide more and more the color of more and more rows become yellow
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")! as! CustomTableViewCell
        let text = data[indexPath.row]
        cell.paramNameLabel.text = text
        cell.paramValueLabel.text = text
        
        if indexPath.row%2 == 0{
            cell.contentView.backgroundColor = UIColor.yellow
        }
        return cell
    }
    
  • PREVENTION method , Always reinitialize each property again and again each time, using cellForRowAt function
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")! as! CustomTableViewCell
      let text = data[indexPath.row]
      cell.paramNameLabel.text = text
      cell.paramValueLabel.text = text
      
      if indexPath.row%2 == 0{
          cell.contentView.backgroundColor = UIColor.yellow
      }
      else{
          cell.contentView.backgroundColor = UIColor.white
      }
      return cell
  }
  
  ```
8. Obtain the cell from indexPath by below function
  let cell = tableView.cellForRow(at: indexPath)!


Steps for a custom Table View Cell

  1. New-> iOS -> CocoaTouch Class -> Next -> name class as CustomTableViewCell -> Subclass of UITableViewCell -> no need to select XIB if you are have .storyboard -> Next
  2. Go to .storyboard -> select TableView Cell -> go to identity Inspector and name the class in Custom Class as CustomTableViewCell
    • After this step you can create IBOutlet of any content that's inside TableViewCell
  3. Insert Label or any other object class inside Table View and make the IBOutlet of that in CustomTableViewCell class
  4. Make the cell variable in CellForRowAt function explicitly to CustomTableViewCell
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")! as! CustomTableViewCell
    
    • Now you can easily set the values of the content inside tableView using IBoutlet example:
    cell.label.text = "name"
    
  5. You can also create the layout using .xib file
    • first create .xib file
    • insert below code in viewDidLoad method
    paramTableView.register(<#T##nib: UINib?##UINib?#>, forCellReuseIdentifier: <#T##String#>)
    
  6. How to know the row no and section no inside any IBAction of CustomViewCell
  • In your UITableViewCell :
     class ExampleCell: UITableViewCell {
        //create your closure here  
             var buttonPressed : (() -> ()) = {}
    
            @IBAction func buttonAction(_ sender: UIButton) {
        //Call your closure here 
                buttonPressed()
            }
        }
    
  • In your ViewController
  class ViewController:  UIViewController,  UITableViewDataSource, UITableViewDelegate {
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath) as! ExampleCell
     cell.buttonPressed = {
            //Code
             }
  return cell 
    }
  }

Add fuctionality of Interaction with TableViewCell like Selecting cell or any other

  1. Make ViewController as delegate of UITableViewDelegate

      class ParameterTuningViewController: UITableViewController, UITableViewDelegate
    
  2. Add below line in ViewDidLoad

      IBOutletTableView.delegate = self
    
  3. add below function to present alert controller when selected a table view cell

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      tableView.deselectRow(at: indexPath, animated: true)
      let alertController = UIAlertController(title: "Hint", message: "You have selected row no \(indexPath.row) and section no \(indexPath.section)", preferredStyle: .alert)
      let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
      alertController.addAction(alertAction)
      present(alertController, animated: true, completion: nil) // UITableViewDelegate
      
    }