unable to customize tableView for side menu in swift

Viewed 158

I want to add spacing between rows and set the header here my code is -

    @IBOutlet weak var sideMenu: UITableView!
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TownTalkTableViewCell
         cell.logo.setImage(arr[indexPath.row]["icon"] as? UIImage, for: .normal)
        cell.grupName.text = array[indexPath.row]["groupname"] as? String

     return cell
2 Answers

First Add tableview Delegate and Data Source for both tableview in storyboard by taping control+draging into viewcontroller

enter image description here Then use the same delegate function to access sidemenu tableview.

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var sideMenu: UITableView!

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableview == sideMenu{
        return 2
    }else{
        //this is for tableView
        return 3
    }
}
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableview == sideMenu{
            //use slide menu tableview cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TownTalkTableViewCell
            cell.grupImage.image = array[indexPath.row]["groupImage"] as? UIImage
            cell.grupName.text = array[indexPath.row]["groupname"] as? String
            return cell
        }else{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TownTalkTableViewCell
            cell.grupImage.image = array[indexPath.row]["groupImage"] as? UIImage
            cell.grupName.text = array[indexPath.row]["groupname"] as? String
            return cell
        }
       
    }
      

2 ways.

  1. make the view controller data source & delegate for both the tableviews & in the methods add the below check.

    if tableview === self.tableview { //its for table view

    return ... } // else its for side menu

    return ...

  2. Create a separate class (Call it SideMenuTableViewHelper or something) for SideMenu tableView datasource & delegate.

First one is simpler, 2nd one is cleaner for datasource, messier for handling delegate (did select row) methods as they will most likely be triggering code in view controller (which can be done via View controller acting as custom delegate to the SideMenuTableViewHelper). For a beginner, I reckon go with (1).

Related