在多个单元格选择 Swift 中自动更改背景颜色

Posted

技术标签:

【中文标题】在多个单元格选择 Swift 中自动更改背景颜色【英文标题】:Background colours changing automatically in Multiple Cell Selection Swift 【发布时间】:2018-10-30 06:45:42 【问题描述】:

我有一个表格视图。我正在使用多个单元格选择。一切正常,功能方面,但 UI 方面却不是。每当我选择一个单元格并向下滚动时,我都会看到下面另一个单元格的颜色发生了变化,尽管该单元格从未被实际选中。我为单元所做的就是这个:

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



还有,这里是代表。

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
    


当数字低到 4 或 5 并且滚动没有出现时,一切都很好,但是一旦它们像 20-22 那样,我就会遇到这个问题。有什么帮助吗?

【问题讨论】:

这是由于可重复使用的单元格而发生的? @VDPurohit 是的,我 100% 确定。 你需要了解重用的概念。如果您对单元格进行任何更改,除非您反转它,否则它将保持不变。因此,您需要跟踪选择了哪一个,并使用 if else 条件来设置颜色。 如前所述,您需要先了解可重用的概念。还请查看以下类似的答案可能有助于解决。 ***.com/questions/52753084/…. 【参考方案1】:

您应该在 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 中处理背景颜色。 检查并使用下面的代码。希望它会工作

 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()




【讨论】:

类似的做法,但颜色不会立即改变我必须上下滚动然后它会改变,有点冻结。 只需在 didSelect 方法中重新加载表即可。 你不觉得如果我每次都重新加载表格,我已经可以选择选定的单元格了。 使用selecetedcells 数组可以管理didSelect 中的所有内容。无需将单元格保持在选中状态 好的,我已经按照你的方式工作了,但是现在didDeselectRow 的颜色没有改变。有什么帮助吗?【参考方案2】:

请在“CellForRowAtIndexPAth”中选择您的默认颜色和选定颜色。请检查以下代码。

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

    

【讨论】:

在问这个问题之前我做了同样的事情,它可以工作,但只有当我滚动时颜色才会改变,非常奇怪。有什么解决办法吗? 我没有使用任何prepareForReuse。我该如何使用它? @RakeshaShastri 我试过了,但没有用。 @RakeshaShastri 在问题中更新了我现在在做什么,请检查。【参考方案3】:
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
    

这可能会有所帮助

【讨论】:

以上是关于在多个单元格选择 Swift 中自动更改背景颜色的主要内容,如果未能解决你的问题,请参考以下文章

UITableView 选择单元格时所有组件都更改了背景颜色

在 Swift 中选择行时删除标签背景颜色

更改 UITableViewRowAction 内的单元格背景颜色

Swift:点击一个单元格时更改所有 UITableViewCells 的文本颜色

怎么在excel中一个单元格中显示出自动计算的标记背景颜色的单元格数值的和

使用 Google 表格下拉菜单更改单元格背景颜色而不是文本