【问题标题】:Change the sections header background color in UITableView using an array of headers使用标题数组更改 UITableView 中的部分标题背景颜色
【发布时间】:2015-07-26 06:17:17
【问题描述】:

我有一个我使用的标题数组

let sectionHeaderTitleArray = ["test1","test2","test3]

它们显示使用

func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
} 

现在所有这些都可以正常工作,但我想修改标题的背景颜色,以便它们更明显(深色)

任何想法,如果我可以在一个简单的行中做到这一点,或者我是否需要使用自定义单元格来创建这个

谢谢

更新

  //number of sections and names for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sectionHeaderTitleArray.count
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionHeaderTitleArray[section] as String
    }
    func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
        return self.tableView.backgroundColor = UIColor.lightGrayColor()
    }

【问题讨论】:

  • 好吧,当它需要一个 UIView 时,你正在返回一个 UIColor..
  • 你需要用returnedView.backgroundColor = UIColor.lightGrayColor() 来设置,这里returnedView是你在func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView中初始化的UIView?
  • 查看我的更新答案
  • 您将不得不根据您使用的数据手动计算 y 值,x 值可以为 0,宽度值为 UIScreen.mainScreen().bounds.size.width 和高度将在 10.0 左右(根据自己的喜好玩)

标签: ios uitableview swift ios8


【解决方案1】:

Swift5

版本更新到 iOS 11,12,13,14 并附上示例

改变背景颜色和文字颜色:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let tableView = view as? UITableViewHeaderFooterView else { return }
    tableView.textLabel?.textColor = UIColor.white
    tableView.contentView.backgroundColor = UIColor.black
}

视图控制器的完整示例:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    private let array: [String] = ["ab","bc","cd","de","ef","fg","gh","hi","ij","jk"]
    let sectionHeaderTitleArray = ["test1","test2", "test3"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 11, *) {}
        else {
            self.edgesForExtendedLayout = []
        }
        configTableview()
    }
    
    private func configTableview() {
        tableView.registerCell(type: SyncCell.self)
        tableView.separatorColor = #colorLiteral(red: 0, green: 0.3066673801, blue: 1, alpha: 0.19)
        tableView.delegate = self
        tableView.dataSource = self
    }
}


extension ViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        guard let tableView = view as? UITableViewHeaderFooterView else { return }
        tableView.textLabel?.textColor = UIColor.white
        tableView.contentView.backgroundColor = UIColor.black
    }
    
    func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
        return sectionHeaderTitleArray[section]
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected cell: \(indexPath)")
    }
}

extension ViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = array[indexPath.row]
        let cell = tableView.dequeueReusableCell(type: SyncCell.self, forIndexPath: indexPath)
        cell.configCell(text: item)
        cell.selectionStyle = .none
        return cell
    }
    
}

【讨论】:

  • 背景颜色没有改变任何标签它工作的建议?
  • 你的 iOS 版本是多少?
  • 版本更新到 iOS 11,12,13,14 示例
【解决方案2】:

没有必要使用诸如 willDisplayHeaderView 方法或其他方法的技巧。 只需创建自己的 UITableViewHeaderFooterView 类。 然后在func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? 返回您创建的自定义标题视图。您不应该直接为您的标题视图更改背景颜色,而是为您的标题视图的 contentView 更改背景颜色?

let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: NotificationSettingsHeaderView.reuseIdentifier) as! NotificationSettingsHeaderView
headerView.label.text = dataSource.snapshot().sectionIdentifiers[section].title
headerView.contentView.backgroundColor = .red
return headerView

更好的是在标题视图子类的init 中设置背景颜色

【讨论】:

    【解决方案3】:

    如果您有自定义标题视图,您可以使用contentView.backgroundColor

    【讨论】:

      【解决方案4】:

      我们可以使用下面的代码 sn-p 更改 tableView 部分的页脚颜色。

      1. 调用方法 heightForFooterInSection

        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { 返回 5.0 }

      2. 调用viewForFooterInSection方法

        func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { 让 viw = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 5)) viw.backgroundColor = .white 返回视图 }

      希望这会对您有所帮助。这是经过测试的代码。

      【讨论】:

      • 两种方法的高度应该相等
      • 欢迎来到 SO。如果您可以使用 SO 的内置代码格式化工具来格式化代码部分,那就太好了。
      • 下次我会@KarthickRamesh
      【解决方案5】:

      如果您只使用 titleForHeaderInSection :

      func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
          (view as! UITableViewHeaderFooterView).contentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
          (view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.white
      }
      

      【讨论】:

      • 最简单、最好的答案。正是我想要的。
      • 最简单的答案。谢谢。
      • 我的答案!谢谢。
      • 这是我想去的地方。
      • 这是我第二次来这里了。如果我可以投票两次。
      【解决方案6】:

      Swift 5 iOS 13

      //Remove 'override' if you don't override from UITableviewController
      override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
          guard let headerView = view as? UITableViewHeaderFooterView else { return }
          headerView.tintColor = .clear //use any color you want here .red, .black etc
      }
      

      【讨论】:

      • 只提供不解释的代码是没有帮助的。我看不到接受的答案中未包含的添加内容。
      • 您可以查看文档以获取更多信息,或者我可以向您推荐一些书籍您觉得如何?让我知道我能做到:)
      • @Dragonthoughts 是错误的,tintColor 是我丢失的拼图。这是正确的答案。谢谢阿德里亚蒂克!
      【解决方案7】:

      重写或实现函数tableview will display

      public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
              let headerView = (view as? UITableViewHeaderFooterView)
              headerView?.tintColor = .clear
          }
      

      【讨论】:

        【解决方案8】:

        而不是使用

        func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String?
        

        数据源方法,可以使用

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
        

        委托方法并简单地自定义返回的UIView

        例如,将 UILabel textLabel 的文本设置为所需的值,将 backgroundColor 的文本设置为所需的 UIColor

        func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let returnedView = UIView(frame: CGRectMake(x, y, width, height)) //set these values as necessary
            returnedView.backgroundColor = UIColor.lightGrayColor()
        
            let label = UILabel(frame: CGRectMake(labelX, labelY, labelWidth, labelHeight))
            label.text = self.sectionHeaderTitleArray[section]
            returnedView.addSubview(label)
        
            return returnedView
        }
        

        SWIFT 5

        override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                    let returnedView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) //set these values as necessary
                    returnedView.backgroundColor = .white
        
                    let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
        
                    label.text = self.sectionHeaderTitleArray[section]
                    returnedView.addSubview(label)
        
                    return returnedView
                }
        

        【讨论】:

        • 谢谢,但我可以在其中使用我的部分标题数组
        • 所以按照我的建议将 textLabel.text 属性设置为所需的部分标题:)
        • 我需要我的所有部分都具有相同的浅灰色
        • 因此将 backgroundColor 设置为所需的 UIColor(在您的情况下为 lightGrey)
        • 将背景颜色直接设置为标题视图会引发运行时警告Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
        【解决方案9】:

        斯威夫特 5

        override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        
            guard let headerView = view as? UITableViewHeaderFooterView else { return }
        
            headerView.backgroundView?.backgroundColor = .red
        }
        

        而且,如果您希望每个部分有不同的标题背景(和/或文本)颜色:

        override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        
            guard let headerView = view as? UITableViewHeaderFooterView else { return }
        
            switch section {
        
            case 0:
                headerView.backgroundView?.backgroundColor = .red
                headerView.textLabel?.textColor = .white
            case 1:
                headerView.backgroundView?.backgroundColor = .green
                headerView.textLabel?.textColor = .white
            case 2:
                headerView.backgroundView?.backgroundColor = .yellow
                headerView.textLabel?.textColor = .black
        
                // etc
        
            default:
                return
            }
        

        【讨论】:

          【解决方案10】:

          覆盖 viewForHeaderInSection 并创建 UITableViewHeaderFooterView

           override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
              var headrview = tableView.dequeueReusableHeaderFooterView(withIdentifier: "aaa")
              if headrview == nil {
                  headrview = UITableViewHeaderFooterView(reuseIdentifier: "aaa")
              }
              let bview = UIView()
              bview.backgroundColor = Theme.current.navigationColor
              headrview?.backgroundView = bview
              headrview?.textLabel?.textColor = Theme.current.primaryTextColor
              return headrview
          }
          

          【讨论】:

            【解决方案11】:

            Swift 4.X

            这是经过测试和工作的代码。

            func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
                return UITableViewAutomaticDimension
            }
            
            func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
                return "Total Count (41)"
            }
            
            func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
                view.tintColor = UIColor.lightGray
                let header = view as! UITableViewHeaderFooterView
                header.textLabel?.textColor = UIColor.darkGray
                header.textLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
            }
            

            【讨论】:

            • 你好,用tintColor的背景怎么改?不错的解决方案,我尝试使用 backgroundview.backgroundColor 但它没有用谢谢!
            • 谢谢伙计!设置 tintColor 对我有用。
            【解决方案12】:

            Swift 4 解决方案。

                override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                let headerView:UIView = UIView()
                    headerView.backgroundColor = UIColor.lightGray
               return headerView
            }
            

            【讨论】:

              【解决方案13】:

              如果你使用titleForHeaderInSection,那么最简单的方法是在viewDidLoad()中添加:

              self.tableView.backgroundColor = UIColor.clear
              

              由于某种原因,在 Interface Builder 的 TableView 的 View 部分中为 Background 设置 ClearColor 并不总是将其设置为透明。但是在代码中添加这一行(至少对我而言)确实如此。

              【讨论】:

                【解决方案14】:

                这将为您的应用程序中的所有标头更改它:

                UITableViewHeaderFooterView.appearance().backgroundColor = theme.subViewBackgroundColor
                

                【讨论】:

                  【解决方案15】:

                  SWIFT 4

                  超级简单,通过设置标题的视图,contentView 背景颜色..

                  override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                     let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerId") as! CustomHeader
                     header.contentView.backgroundColor = AnyColor
                     return header
                  }
                  

                  【讨论】:

                  • 这个答案有点不完整,但似乎是正确的方法。我将如何首先创建具有唯一 ID 的自定义标题视图?目前我在网上看到了很多方法,它们只使用一个自定义创建的单元格来返回该单元格的内容视图。可以扩大一点吗?
                  • 我发现这个答案是迄今为止最干净的。
                  【解决方案16】:

                  你必须保持两者

                  titleForHeaderInSection

                  viewForHeaderInSection

                  这是 Swift 3

                  中的一些工作代码
                  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
                      return self.sectionHeaderTitleArray[section]
                  }
                  
                  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                      let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25))
                      returnedView.backgroundColor = .lightGray
                  
                      let label = UILabel(frame: CGRect(x: 10, y: 7, width: view.frame.size.width, height: 25))
                      label.text = self.sectionHeaderTitleArray[section]
                      label.textColor = .black
                      returnedView.addSubview(label)
                  
                      return returnedView
                  }
                  

                  【讨论】:

                    【解决方案17】:

                    Swift 3+

                    我用过这个:

                    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 20))
                        headerView.backgroundColor = .lightGray
                    
                        let label = UILabel()
                        label.translatesAutoresizingMaskIntoConstraints = false
                        label.text = stringValues[section]
                        headerView.addSubview(label)
                        label.leftAnchor.constraint(equalTo: headerView.leftAnchor).isActive = true
                        label.rightAnchor.constraint(equalTo: headerView.rightAnchor).isActive = true
                        label.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
                        label.heightAnchor.constraint(equalToConstant: 25).isActive = true
                    
                        return headerView
                    
                    }
                    

                    【讨论】:

                      猜你喜欢
                      • 2013-01-03
                      • 2023-03-04
                      • 2010-10-23
                      • 1970-01-01
                      • 2012-09-10
                      • 2013-11-19
                      • 2011-03-18
                      • 1970-01-01
                      相关资源
                      最近更新 更多