简体   繁体   English

如何更改选定的可扩展表格视图单元格的背景颜色

[英]How to change the background color of selected expandable table view cell

I need to change the background color in expandable table view cell, when it is selected. 选择它后,我需要在可扩展表格视图单元格中更改背景色。 What I have done is, I placed three UIViews in a cell. 我要做的是,在一个单元格中放置了三个UIView。 When the first view in the cell is selected, the remaining two views will be expanded. 选择单元格中的第一个视图时,其余两个视图将被展开。 It is working. 这是工作。 Now I need to change the color of the first view alone when a cell is selected. 现在,当选择一个单元格时,我需要单独更改第一个视图的颜色。 Used the following code, it changes the color of third view in the cell. 使用以下代码,它将更改单元格中第三个视图的颜色。 But I want the first view to change and stay in orange color until the other cell is selected. 但是我希望第一个视图改变并保持橙色直到选择其他单元格。 Could anyone help ? 有人可以帮忙吗?

import UIKit
import CoreData

class NewTableViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{

    let viewObj = CustomCellTableViewCell()
    let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    @IBOutlet weak var tableView: UITableView!
     var selectedIndex = -1

     override func viewDidLoad() {
        super.viewDidLoad()
     }

     override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
     }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return totalCustomer().0
     }

     func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) ->CGFloat
     {
        if(selectedIndex == indexPath.row) {
            return 160;
        }
        else {
            return 40;
        }
     }

     func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) ->UITableViewCell{
            print("entered")
            let cellIdentifier = "Cell"
            let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! CustomCellTableViewCell
            let row = indexPath.row
            var nameArray = [String]()
            nameArray = totalCustomer().1
            cell.firstViewLabel.text = nameArray[row]
            var emailArray = [String]()
            emailArray = totalCustomer().2
            cell.secondViewLabel.text = emailArray[row]

            return cell
      }

      func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
         let cell = tableView.cellForRow(at: indexPath)
         cell?.contentView.backgroundColor = UIColor.orange
         cell?.backgroundColor = UIColor.orange
      }

      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
      {             
          if(selectedIndex == indexPath.row) {
              selectedIndex = -1
          } else {
              selectedIndex = indexPath.row
          }
          self.tableView.beginUpdates()
          self.tableView.reloadRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
          self.tableView.endUpdates()
       }

       func totalCustomer()->(Int,[String],[String])
       {
          let request: NSFetchRequest<Customers> = Customers.fetchRequest()
          var customerList = [String]()
          var customerEmailList = [String]()
          var customerCount = 0
          do {
             let results = try managedObjectContext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)
             print(results.count)
             if  results.count > 0
             {
                for _ in 0..<results.count
                {
                   let match = results[customerCount] as! NSManagedObject
                   print(match.value(forKey: "name") as! String)
                   customerList.append(match.value(forKey: "name") as! String)
                   customerEmailList.append(match.value(forKey: "email") as! String)
                   customerCount = customerCount + 1
                 }
             }
             else
             {
                    //statusLabel.isHidden = false
             }

          }
          catch let error
          {
              print("Label\(error.localizedDescription)")
          }
          print(customerCount)
          return (customerCount,customerList,customerEmailList)
      }


}

import UIKit
class CustomCellTableViewCell: UITableViewCell {

    @IBOutlet weak var firstView: UIView!
    @IBOutlet weak var firstViewLabel: UILabel!
    @IBOutlet weak var secondView: UIView!
    @IBOutlet weak var secondViewLabel: UILabel!
    @IBOutlet weak var thirdView: UIView!
    @IBOutlet weak var thirdViewLabel: UILabel!

    @IBOutlet weak var secondHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var thirdHeightConstraint: NSLayoutConstraint!



    override func awakeFromNib() {
        super.awakeFromNib()
        secondView.layer.borderWidth = 0.1
        secondView.layer.borderColor = UIColor.black.cgColor
        thirdView.layer.borderWidth = 0.1
        thirdView.layer.borderColor = UIColor.black.cgColor
    }

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

    }
    var showsDetails = false {
        didSet {
            secondHeightConstraint.priority = showsDetails ? 250 : 999
            thirdHeightConstraint.priority = showsDetails ? 250 : 999

        }
    }
}

Considering that you are storing your selected IndexPath.row in selectedIndex and your firstView is public and you are reloading your UITableView after selecting a cell, the following additional code in cellForRowAt method should be enough. 考虑到您将所选的IndexPath.row存储在selectedIndex并且firstView是公共的,并且在选择一个单元格之后正在重新加载UITableView ,因此cellForRowAt方法中的以下附加代码就足够了。

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

   if self.selectedIndex == indexPath.row {
      cell.firstView.backgroundColor = UIColor.yellow // selected color
   }else {
      cell.firstView.backgroundColor = UIColor.blue // default color
   }    
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{     
      var indexPathArray: [IndexPath] = []
      if selectedIndex != -1 {
         indexPathArray.append(IndexPath(row: selectedIndex, section: 0)) // previous selected row
      }        
      if(selectedIndex == indexPath.row) {
          selectedIndex = -1
      } else {
          selectedIndex = indexPath.row
          indexPathArray.append(indexPath) // currently selected row
      }
      self.tableView.beginUpdates()
      if indexPathArray.count > 0 {
         self.tableView.reloadRows(at: indexPathArray, with: UITableViewRowAnimation.automatic)
      }
      self.tableView.endUpdates()
}

Move the colour changing login to cellForRowAt method. 将更改颜色的登录名移动到cellForRowAt方法。

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

   if self.selectedIndex == indexPath.row {
      cell.firstView.backgroundColor = UIColor.orange  // Highlight color
   }else {
      cell.firstView.backgroundColor = UIColor.blue // Original color
   }    
}

Remember to update the previous row also to remove the background color: 记住要更新前一行,也要删除背景色:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
      {   
           previousIndex = selectedIndex          
          if(selectedIndex == indexPath.row) {
              selectedIndex = -1
          } else {
              selectedIndex = indexPath.row
          }
          var myPrevIP = IndexPath(row: previousIndex, section: indexPath.section)
          var indexPathArray: [Any] = [myPrevIP, indexPath]
          self.tableView.beginUpdates()
          self.tableView.reloadRows(at:indexPathArray,with: UITableViewRowAnimation.automatic)
          self.tableView.endUpdates()
       } 

UITableView already has the selection mechanism implemented. UITableView已经实现了选择机制。

In your cell, you can control your background color: 在单元格中,您可以控制背景色:

class MyCustomCell: UITableViewCell {
    @IBInspectable var normalColor: UIColor = UIColor.white
    @IBInspectable var highlightedColor: UIColor = UIColor.red
    @IBInspectable var selectedColor: UIColor = UIColor.blue

    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)
        refreshBackground()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        refreshBackground()
    }

    func refreshBackground() {
        if isHighlighted {
            backgroundColor = highlightedColor
        }
        else if isSelected {
            backgroundColor = selectedColor
        }
        else {
            backgroundColor = normalColor
        }
    }
}

And using @IBInspectable in the cell let's you configure the colors directly in storyboard. 在单元格中使用@IBInspectable ,您可以直接在情节@IBInspectable中配置颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM