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

时间:2017-01-16 14:43:56

标签: ios swift

我需要更改可扩展表格视图单元格中的背景颜色。我所做的是,我在一个单元格中放置了三个UIViews。选择单元格中的第一个视图时,将展开剩余的两个视图。这是工作。现在,我需要在选择单元格时单独更改第一个视图的颜色。使用以下代码,它更改单元格中第三个视图的颜色。但我希望第一个视图更改并保持橙色,直到选中另一个单元格。有人可以帮忙吗?

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

        }
    }
}

3 个答案:

答案 0 :(得分:2)

考虑到您将所选的open FSharp.Data [<Literal>] let JsonPath = "https://facebook.github.io/react-native/movies.json" type Car = { Title:string ; ReleaseYear:int } type MovieProvider = JsonProvider<JsonPath> let getCars() = async { let! result = MovieProvider.AsyncLoad JsonPath return result.Movies |> Array.toList |> List.map (fun m -> { Title=m.Title; ReleaseYear=m.ReleaseYear }) } 存储在IndexPath.row并且selectedIndex是公开的,并且您在选择单元格后重新加载firstView,请输入以下附加代码UITableView方法应该足够了。

cellForRowAt

答案 1 :(得分:1)

将颜色更改登录名移至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
   }    
}

请记住也要更新上一行以删除背景颜色:

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

答案 2 :(得分:1)

UITableView已经实施了选择机制。

在您的单元格中,您可以控制背景颜色:

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
        }
    }
}

在单元格中使用@IBInspectable,您可以直接在故事板中配置颜色。

相关问题