GRDY
GRDY

Reputation: 55

How do select a row from each section of the tableview in swift?

I want to select a row from different sections of the same table-view. I am getting output that many rows are selecting but I want exactly only one selected row from each section.

Here is My Arrays:

var filterFeedUnderAll = ["Complex","NotComplex","Easy"]
var filterFeedUnderAllStocks = ["AllStocks","Portfolio","Watchlist","Sector","Ticker"]
var filterFeedUnderByDate = ["ByDate","ByComments","ByLikes"]

The methods I have used:

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 3
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    var count:Int?
    if section == 0
    {
        count = filterFeedUnderAll.count
    }
    else if section == 1
    {
        count = filterFeedUnderAllStocks.count
    }
    else if section == 2
    {
        count = filterFeedUnderByDate.count
    }
    return count!
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = self.m_HomeFeedFilterBaseTableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! HomeFeedFIlterBaseTableViewCell
    switch (indexPath.section)
    {
    case 0:
        cell.m_TableItemsLabel.text = filterFeedUnderAll[indexPath.row]
    case 1:
        cell.m_TableItemsLabel.text = self.filterFeedUnderAllStocks[indexPath.row]
    case 2:
        cell.m_TableItemsLabel.text = filterFeedUnderByDate[indexPath.row]
    default:
        cell.m_TableItemsLabel.text = "Other"
    }
    return cell
}


  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
   {
      let cell = m_HomeFeedFilterBaseTableView.cellForRowAtIndexPath(indexPath) as! HomeFeedFIlterBaseTableViewCell
      for selectedIndexPath: NSIndexPath in tableView.indexPathsForSelectedRows! 
      {
      if selectedIndexPath.section == indexPath.section
      {
      cell.m_TableItemsLabel.textColor = selectedTextColor
      tableView.deselectRowAtIndexPath(indexPath, animated: true)
      }
    }

}

I want to select one row from each section. Help me to achieve this task.

Upvotes: 4

Views: 7969

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

first of all you need to enable multiple selection in your tableView and then this is the code that I used to do that, note that I use a Dictionary with format [String:NSIndexPath] named selectedRows where I store one indexPath by section I do this in addSelectedCellWithSection

UPDATED for last swift

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate {

    @IBOutlet weak var tableView: UITableView!

    var filterFeedUnderAll = ["Complex","NotComplex","Easy"]
    var filterFeedUnderAllStocks = ["AllStocks","Portfolio","Watchlist","Sector","Ticker","bla bla bla1","bla bla bla2","bla bla bla3","bla bla bla1","bla bla bla2","bla bla bla3","bla bla bla1","bla bla bla2","bla bla bla3"]
    var filterFeedUnderByDate = ["ByDate","ByComments","ByLikes"]

    var selectedRows = [String:IndexPath]()

    var alert : UIAlertController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 3
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50;
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     let  headerCell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! mycustomHeader


     let layer = CAShapeLayer()
     let corners = UIRectCorner.topLeft.union(UIRectCorner.topRight)
     layer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: headerCell.frame.width, height: headerCell.frame.height), byRoundingCorners: corners, cornerRadii:CGSize(width: 20.0, height: 20.0)).cgPath
     headerCell.layer.mask = layer
     return headerCell
     }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        var count:Int?
        if section == 0
        {
            count = filterFeedUnderAll.count
        }
        else if section == 1
        {
            count = filterFeedUnderAllStocks.count
        }
        else if section == 2
        {
            count = filterFeedUnderByDate.count
        }
        return count!
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! testCell
        switch (indexPath.section)
        {
        case 0:
            cell.lblName.text = filterFeedUnderAll[indexPath.row]
        case 1:
            cell.lblName.text = self.filterFeedUnderAllStocks[indexPath.row]
        case 2:
            cell.lblName.text = filterFeedUnderByDate[indexPath.row]
        default:
            cell.lblName.text = "Other"
        }
        cell.lblName.textColor = UIColor.black
        if(self.indexPathIsSelected(indexPath)) {
            cell.lblName.textColor = UIColor.red
        }
        return cell
    }

    func addSelectedCellWithSection(_ indexPath:IndexPath) ->IndexPath?
    {
        let existingIndexPath = selectedRows["\(indexPath.section)"]
        selectedRows["\(indexPath.section)"]=indexPath;
        return existingIndexPath
    }

    func indexPathIsSelected(_ indexPath:IndexPath) ->Bool {
        if let selectedIndexPathInSection = selectedRows["\(indexPath.section)"] {
            if(selectedIndexPathInSection.row == indexPath.row) { return true }
        }

        return false
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = self.tableView.cellForRow(at: indexPath) as! testCell

        let previusSelectedCellIndexPath = self.addSelectedCellWithSection(indexPath);

        if(previusSelectedCellIndexPath != nil)
        {
            let previusSelectedCell = self.tableView.cellForRow(at: previusSelectedCellIndexPath!) as! testCell

            previusSelectedCell.lblName.textColor = UIColor.black
            cell.lblName.textColor = UIColor.red
            tableView.deselectRow(at: previusSelectedCellIndexPath!, animated: true)
        }
        else
        {
            cell.lblName.textColor = UIColor.red

        }
        for selectedIndexPath: IndexPath in tableView.indexPathsForSelectedRows!
        {
            if selectedIndexPath.section == indexPath.section
            {
                cell.lblName.textColor = UIColor.red
                tableView.deselectRow(at: indexPath, animated: true)
            }
        }
    }

}

Hope this helps you, for me works perfect

Upvotes: 4

Related Questions