ios - 正在调用 willDisplayHeaderView 但 titleForHeaderInSection 中的文本属性保持不变

标签 ios swift uitableview

我有一个自定义 tableView,下面有 willDisplayHeaderView

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    let tableViewHeaderFooterview = UITableViewHeaderFooterView()
    tableViewHeaderFooterview.textLabel?.font = UIFont.hmFont(13)
    tableViewHeaderFooterview.textLabel?.textColor = UIColor.hmDarkGrey()
}

我有另一个 tableViewController,它是自定义 tableView 的子类,具有下面的 titleForHeaderInSection

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "YOUR SUBSCRIPTION"
    } else if section == 1 {
        return "SIGN OUT"
    }

    return nil
}

我的 willDisplayHeaderView 被调用,但是当我在模拟器上运行我的应用程序时,我没有看到标题 View 标题的变化。过去几个小时我一直在这里寻找答案,但到目前为止还没有解决方案。起初我以为我可能忘记设置我的 delegate/datasource 但那没有用。

最佳答案

让我们看看你的代码

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
  let tableViewHeaderFooterview = UITableViewHeaderFooterView()
  tableViewHeaderFooterview.textLabel?.font = UIFont.hmFont(13)
  tableViewHeaderFooterview.textLabel?.textColor = UIColor.hmDarkGrey()
}

在函数声明中,您有一个名为 view 的 View ,您的函数将通过该 View 调用。换句话说,iOS 正在您的类中查找此函数并说,“我将要显示这个 View ,让您知道。”不过,在您实现的第一行中,您要创建一个名为 tableViewHeaderFooterview 的新 View 并为其设置一些属性。这些更改不会反射(reflect)在 iOS 告诉您的 View 中。

此时您有几个选择:1) 处理 view 的 subview 以寻找标签(乱七八糟的和坏的),2) 尝试将其转换为 UITableHeaderFooterView (if let header = view as? UITableViewHeaderFooterView { header.textLabel.font = whatever }), 或 3) 注册你自己的 UIView 子类并提前配置它:

class MyHeader: UITableViewHeaderFooterView {
  ...
}

override func viewDidLoad() {
  super.viewDidLoad()
  tableView.registerClass(MyHeader.self, forHeaderFooterViewReuseIdentifier: "myHeader")
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  if let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "myHeader") as? MyHeader {
    myHeader.label.text = "YOUR SUBSCRIPTION";
    return myHeader
  }
  return nil
}

关于ios - 正在调用 willDisplayHeaderView 但 titleForHeaderInSection 中的文本属性保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404161/

相关文章:

ios - Swift:将重新排列按钮移至左上角

iOS:更改 UISegmentedcontrol 的高度

ios - 逐帧解码 h264 示例 ios 7

ios - 透明导航栏 swift iOS

iphone - 在静态 TableView 的 UITextfield 中禁用编辑 - 仅限 iOS 6.0

ios - 无需 UITableView 即可模拟表格单元格(重新使用标准 iOS UI)

ios - 回调中分别处理JSON响应数据和String响应数据

ios - Swift:将容器 View 中的几个标签设置为容器的比率/百分比

ios - 非 OS X 用户的 Swift 实验

ios - 当应用程序再次运行时,AVAudioPlayer 不再播放音乐