无法在UITableView中设置自定义标题视图

时间:2017-08-16 17:25:09

标签: ios swift uitableview

我正在尝试为UITableView创建自定义标头,但它显示“致命错误:在展开Optional值时意外发现nil”。代码是这样的:

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
    self.headerImage?.frame = CGRect(x: (headerImage?.frame.size.width)! + 20, y: 20, width: 10, height: 10)
    headerLbl?.frame = CGRect(x: (headerImage?.frame.size.width)! + 20, y: 20, width: 10, height: 10)
    arrowImage?.isHidden = true
    arrowImage?.frame = CGRect(x: menuTableView.frame.size.width - 30, y: 20, width: 10, height: 10)
    if selectedIndex == section {
      arrowImage?.image = UIImage(named: "down arrow")
    } else {
      arrowImage?.image = UIImage(named: "side_arrow")
    }
    let headerClick = UIButton(type: .custom)
    headerClick.addTarget(self, action: #selector(self.headerAction), for: .touchUpInside)
    headerClick.frame = CGRect(x: 0, y: 0, width: menuTableView.frame.size.width, height: 40)
    headerClick.tag = section
    headerClick.backgroundColor = UIColor.clear
    headerView.addSubview(headerImage!)
    headerView.addSubview(headerLbl!)
    headerView.addSubview(arrowImage!)
    headerView.addSubview(headerClick)
    return headerView
  }
  func headerAction(_ sender: UIButton) {
    if selectedIndex == sender.tag {
      selectedIndex = -1
    }
    else {
      selectedIndex = Int(sender.tag)
    }
     menuTableView.reloadData()
  }
}

但是从这段代码中得到的错误如下面的截图所示: enter image description here

为什么我会收到这样的错误。关于它的任何想法?

0 个答案:

没有答案