Search code examples
iosuitableviewswift2multipleselectionuitableviewrowaction

Select and Deselect UITableView Rows


I have TableView with multiple rows, I am selecting them and adding them to the Label text when i deselect any of the row I am unable to remove it from Label Text

Here's My Code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == categoryTable
        {
        let cell = self.categoryTable.dequeueReusableCellWithIdentifier("categoryCell") as! InquiryCategoryTableViewCell

        let Category:CategoryDB = categoryData.objectAtIndex(indexPath.row) as! CategoryDB
        print("Category = \(Category.category)")

            cell.categoryName.text = "\(Category.category)"
            cell.tintColor = color.UIColorFromRGB(0xCEEBFF)
            categoryTable.allowsMultipleSelectionDuringEditing = true
            categoryTable.setEditing(true, animated: false)



        return cell
        }
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if tableView == categoryTable
        {
            categoryList = categoryData[indexPath.row] as! CategoryDB

            self.category_id = categoryList!.catg_id



            print("Name = \(categoryList!.category)")
            print("ID = \(self.category_id)")
            categoryLabel.text! += "\(categoryList!.category), "
        }
}

Here's What i get as Output:

I first selected 3 rows it got appended to Label.text and after i deselect the row Label.text remains same

Anyone who can help me in this code?


Solution

  • you can add a flag - hasSelected in CategoryDB

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if tableView == categoryTable
        {
            categoryList = categoryData[indexPath.row] as! CategoryDB
    
            categoryList!.hasSelected = true
    
            refreshLabel()
        }
    

    }

    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    if tableView == categoryTable
        {
            categoryList = categoryData[indexPath.row] as! CategoryDB
    
            categoryList!.hasSelected = false
    
            refreshLabel()
        }
    

    }

    func refreshLabel(){
         var label = ""
         for object in categoryData as! CategoryDB {
            if(object.hasSelected){
                label += "\(categoryList!.category), "
            }
         }
         categoryLabel.text! = label
    

    }