Background colours changing automatically in Multiple Cell Selection Swift

how to fill a cell with color in numbers
smartsheet strikethrough when complete
conditional formatting smartsheet
numbers change cell color based on value
how to hide gridlines in numbers when printing
uicollectionview scroll one cell at a time swift
uicollectionview scroll horizontal and vertical swift
smartsheet color settings

I have a table view. I am using multiple cell selection. Everything is working correctly, functionality wise, but UI wise it is not. Whenever I select a cell and scroll down I see the color is changed in another cell below though that cell was never actually selected. What I have done is this for the cell:

class FollowSportsCell: UITableViewCell {

@IBOutlet weak var sportL: UILabel!
@IBOutlet weak var backImg: UIImageView!

override func awakeFromNib() {

    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {

    super.setSelected(selected, animated: animated) 
}

override func prepareForReuse() {

    super.prepareForReuse()

    backImg.backgroundColor = UIColor(hexString: "E6E6E6")

    sportL.textColor = .black


}

And, here are delegates.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return sportsArr!.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell                   = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as!                                                                         FollowSportsCell

    let sport                 = sportsArr![indexPath.row]["id"] as! Int

    cell.sportL.text      = sportsArr![indexPath.row]["title"] as? String

    cell.selectionStyle = UITableViewCell.SelectionStyle.none

    if selectedSports.contains(sport) {

        cell.sportL.textColor = .white

        cell.backImg.backgroundColor = UIColor(hexString: "4293CC")

    }

    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    selectedCell += 1

    let sport = sportsArr![indexPath.row]["id"]

    selectedSports.append(sport! as! Int)

    if selectedCell > 1
    {
        collectionB[0].backgroundColor = UIColor(hexString: "4293CC")

        collectionB[0].isEnabled               = true
    }

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    selectedCell -=  1

    selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}

    if selectedCell < 2
    {
        collectionB[0].backgroundColor = .lightGray

        collectionB[0].isEnabled               =  false
    }

}

When, the number is low like 4 or 5 and the scroll doesn't appear everything is good, but once they are like 20-22 then, I get this issue. Any help?

You should handle background color in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) . Check and use below code. Hope it will work

 var selectedCells = Array<NSInteger>()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return sportsArr!.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell             = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell

    cell.sportL.text     = sportsArr![indexPath.row]["title"] as? String

    cell.selectionStyle  = UITableViewCell.SelectionStyle.none

    if self.selectedCells.contains(indexPath.row) {
        cell.sportL.textColor = .white

        cell.backImg.backgroundColor = UIColor(hexString: "4293CC")

        if self.selectedCells.count > 1
        {
            collectionB[0].backgroundColor = UIColor(hexString: "4293CC")

            collectionB[0].isEnabled               = true
        }
    }
    else
    {
        //Here Set your default color for cell backImgr background color
        cell.sportL.textColor = // set default color

            cell.backImg.backgroundColor = // set default color

    }
    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! FollowSportsCell

    if self.selectedCells.contains(indexPath.row) {
        //Here you will get selected cell and going to deselect...Do anything with deselection

        if let index = self.selectedCells.index{$0 == indexPath.row}
        {
          self.selectedCells.remove(at: index)
        }

        cell.sportL.textColor = .black

        cell.backImg.backgroundColor = UIColor(hexString: "E6E6E6")

        selectedCell -=  1

        selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}

        if self.selectedCells.count < 2
        {
            collectionB[0].backgroundColor = .lightGray

            collectionB[0].isEnabled               =  false
        }

    }
    else
    {
        self.selectedCells.append(indexPath.row)
        print(cell.sportL.text!)

        selectedCell += 1

        let sport = sportsArr![indexPath.row]["id"]

        selectedSports.append(sport! as! Int)
    }

    self.yourtblView.reloadData()



}

SWIFT 4, XCODE 9, IOS 11 Style: Grouped, Selection: Multiple Selection You may notice the icon and text color also changing when cell is selected. This happens automatically when you set the UIImage and UILabel Highlighted  47. 10. // Doesn't workcell.selectionStyle = .Blue//Works when the selection is not multiple, if it's multiple with each selection the previous one disappearlet cellBGView = UIView()cellBGView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.4)cell.selectedBackgroundView = cellBGView.

Please select your default and selected color in "CellForRowAtIndexPAth". Please check the below code.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell             = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
    cell.sportL.text     = sportsArr![indexPath.row]["title"] as? String
    cell.selectionStyle  = UITableViewCell.SelectionStyle.none

    let sport = sportsArr![indexPath.row]["id"]
    cell.sportL.textColor = default cell colour
    cell.backImg.backgroundColor = default cell colour


    if selectedSports.contain(sport) {
            cell.sportL.textColor = required cell colour
            cell.backImg.backgroundColor = required cell colour

    }
    return cell

    }

Conditional formatting rules apply formatting automatically to rows or cells To change cell values based on criteria, you'll want to use a formula. For example, if you'd like to apply a background color to all rows assigned to Joe, select the When the rule is set up to apply formatting to multiple columns, you'll see an  What if the row color before selection was not white? – Thunder May 25 '12 at 11:29 I mean that was just a quick sample to illustrate the concept -- you just create a helper method to retrieve whatever color you need to toggle there.

import UIKit

class TableVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var tableView : UITableView!

   var arrayOfTitle : [titleOfArray] = [titleOfArray]()

   override func viewDidLoad() {
        super.viewDidLoad()

        if self.tableView != nil {
            self.tableView.delegate = self
            self.tableView.dataSource = self
        }

        for i in 0...20 {
            self.arrayOfTitle.append(titleOfArray(title: "Test\(i)", isSelectedIndex: false))
        }

        // Do any additional setup after loading the view.
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 80
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.arrayOfTitle.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel!.text = self.arrayOfTitle[indexPath.row].title
        cell?.textLabel!.textColor =  self.arrayOfTitle[indexPath.row].isSelectedIndex ? UIColor.red : UIColor.blue
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        for i in 0...self.arrayOfTitle.count-1 {
            self.arrayOfTitle[i].isSelectedIndex = false
        }
        self.arrayOfTitle[indexPath.row].isSelectedIndex = true
        tableView.reloadData()
    }
}


class titleOfArray : NSObject {

    var title : String!
    var isSelectedIndex : Bool!

    init(title:String! ,isSelectedIndex :Bool) {

        self.title = title
        self.isSelectedIndex = isSelectedIndex
    }
}

this might be helpful

From the Resolve Auto Layout Issues icon popup, choose Add On the Attributes Inspector of the Collection View, change the Scroll Direction to horizontal. 6. Switch to the Collection View Cell and set its background color to red. 7. the selected cell by category?, becouse i can get the cell selected but not  Once changed, the background color will remain the same, regardless of the cell values' changes. If you want to change the color of blank cells or cells with formula errors permanently, follow this way. Select your table or a range and press F5 to open the " Go To " dialog, and then click the " Special… " button.

In Pages on your Mac, highlight text for review in the body of your document, in text When multiple people are working on a document, each person's highlights that are visible in your final document, add a background colour to text in any colour. To learn how to change your highlight colour, see Set author name and  Swift 4. To change the background color, text label color and font for the Header View of a UITableView Section, simply override willDisplayHeaderView for your table view like so: override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as!

Update note: Kevin Colligan updated this tutorial for Xcode 10, iOS 12 and Swift 4.2. Joshua Use Auto Layout for the UI elements inside the table view cells. Open Main.storyboard, select the bio label and choose a lighter color for the text. Then, in the Size inspector, change the Row Height to 450. Actually, it is what does the trick and applies formatting to the whole row based on a value in a given cell. Click the " Format… " button and switch to Fill tab to choose the background color. If the default colors do not suffice, click the " More Colors… " button to pick the one to your liking, and then click OK twice.

Learn how to make expanding cells in iOS collection views, as in the Ultravisual app. The starter project uses the color palette and, in a future step, you'll These two lines were the basic layout to show the equally sized multi-colored cells. Now for a few Auto Layout constraints: Select the Add New  And then click OK > OK to close the dialogs, repeat steps 5 to 7 for each other drop down selection, for example, Peach for pink, Grape for purple…. 5. After setting the colors for the values, when you choose anyone value from the drop-down menu, the cell will be colored with its specified color automatically.

Comments
  • it's happen due to reusable cell?
  • @VDPurohit Yes, I am 100% sure.
  • You need to understand the reusing concept. If you are making any change to a cell, it will stay like that only unless you invert it. So you need to keep track which one is selected and use if else condition to set the color otherwise.
  • As mentioned above you need to understand reusable concept first. Also look into following similar answer may helps to solve. stackoverflow.com/questions/52753084/….
  • Kind of doing the same, but the color is not changing immediately I have to scroll up and down and then it changes, kind of freezes.
  • Just reload table in didSelect method.
  • Don't you think if I will reload the table everytime, I will be able to select the selected cell already.
  • Using selecetedcells array you can manage everything in didSelect..no need to keep cell in selected state
  • Ok, I have done your way it works, but now for didDeselectRow the colors are not changing. Any help regarding that?
  • I did the very same before asking this question, it works but the color changes only when I scroll, very weird. Any solution for this?
  • I am not using any prepareForReuse. How can I use it?
  • @RakeshaShastri I tried it out, but was not working.
  • @RakeshaShastri Updated what am I doing now in the question please check.