Swift: Can't edit properties of custom table cell programmatically

后端 未结 2 788
死守一世寂寞
死守一世寂寞 2021-01-21 10:45

I am trying to change the colour of a view inside a custom table cell and I have an outlet to it, which works. I can change other properties of this view, like .isHidden

相关标签:
2条回答
  • 2021-01-21 11:24

    Thanks a lot for all the suggestions, I ended up going with the solution that bsod suggested and I'd like to provide more details for anyone who needs this in the future. Rob's solution didn't work for me.

    1. Duplicate the first custom cell inside the tableview and stylise it however you want.

    1. Create a second class and assign it to the second cell, as well as a new identifier. You can also create any outlets you need in this second class and they can have the same name.

    1. In the cellForRowAt indexPath method, I've used an if statement to dequeue the custom cells based on whether a chapter is completed or not and then style them accordingly. This repeats some code but the cell has to be type cast to work (if anyone can think of a way to do this better, I'm open to alternatives).

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

      if chapters[indexPath.row].completed == false {
          let cell = tableView.dequeueReusableCell(withIdentifier: "RegularCell") as! RegularCell
      
          cell.chapterLabel?.text = chapters[indexPath.row].generateTitle()
          cell.chapterNumber?.text = "#\(indexPath.row + 1)"
      
          if chapters[indexPath.row].locked == true {
              cell.chapterLabel?.alpha = 0.3
              cell.chapterNumberContainer?.alpha = 0.3
          } else {
              cell.chapterLabel?.alpha = 1
              cell.chapterNumberContainer?.alpha = 1
          }
      
          let cellBGView = UIView()
          cellBGView.backgroundColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 0.1)
          cell.selectedBackgroundView = cellBGView
          smallLabel(cell.chapterLabel, 18)
          cell.keepSubviewBackground = true
      
          return cell
      } else {
          let cell = tableView.dequeueReusableCell(withIdentifier: "CompletedCell") as! CompletedCell
      
          cell.chapterLabel?.text = chapters[indexPath.row].generateTitle()
      
          let cellBGView = UIView()
          cellBGView.backgroundColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 0.1)
          cell.selectedBackgroundView = cellBGView
          smallLabel(cell.chapterLabel, 18)
          cell.keepSubviewBackground = true
      
          return cell
      }
      
    0 讨论(0)
  • 2021-01-21 11:43

    Check this,It can be an issue here. UITableViewCell textLabel color not changing Notes:Can't comment for less reputation.That's why posted it as an answer.

    0 讨论(0)
提交回复
热议问题