swift 更改表视图中的部分数组元素文本或字体颜色 header

swift change section array element text or font color in tableview header

我的表格视图代码是-

    import UIKit

    class ViewController: UIViewController {
    var categories = ["Action", "Drama", "Science Fiction", "Kids", "Horror"]
   }
   extension ViewController : UITableViewDelegate { }

   extension ViewController : UITableViewDataSource {
     func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) ->      String? {
    return categories[section]
  }

  func numberOfSections(in tableView: UITableView) -> Int {
    return categories.count
  }



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

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->     UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoryRow
    return cell
    }

 }

模拟器上的结果是-

现在,我想要自定义各个部分的 font/text,即动作、戏剧、科幻小说、儿童、除黑色以外的恐怖,可能会使其更大等。这怎么可能?

UITableViewDelegate

中有以下功能可用
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        <#code#>
    }

您可以完全控制每个部分的 header 并且可以相应地进行自定义。

方法中

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) ->      String? {
return categories[section]

table 视图对部分 header 标题使用固定字体样式。如果您想要不同的字体样式,return 委托方法 tableView(_:viewForHeaderInSection:) 中的自定义视图(例如,UILabel object)。

您可以使用 UITableView tableView(_:viewForHeaderInSection:) 的委托方法为 header

获取自定义 UI
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

       let headerView = UIView(frame: CGRect(x: 0, y: 0, width: yourTable.bounds.width, height: 40))
       let headerLabel = UILabel(frame: CGRect(x: 15, y: 0, width: yourTable.bounds.width, height: 40))
       headerLabel.font = UIFont.boldSystemFont(ofSize: 20)
       headerLabel.textColor = .blue

       headerLabel.text = self.tableView(self.yourtableView, titleForHeaderInSection: section)
       headerLabel.sizeToFit()
       headerView.addSubview(headerLabel)

       return headerView
}

以及部分的高度

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 

        return 30 //whatever you want

}

使用 tableView(_:titleForHeaderInSection:) 方法,您无法修改 header 文本的 UI 属性。

您需要实施 tableView(_:viewForHeaderInSection:)tableView(_:heightForHeaderInSection:) 方法以获得 header 的自定义 UI,即

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let label = UILabel()
    label.text = categories[section]
    label.font = UIFont.systemFont(ofSize: 20.0, weight: .bold)
    label.textColor = .red
    label.sizeToFit()
    return label
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50.0
}

只需 return 一个 UILabel 实例,在 tableView(_:viewForHeaderInSection:)

中具有所需的文本属性