在之前使用 ObjectiveC 的项目中,我有一个多节 tableView 显示具有不同背景颜色的节标题以及根据节内项目数动态更新自身的标题文本。它工作得很好。我试图在我们使用 Swift 的新项目中复制此代码,但它不起作用。标题文本正确显示,但没有背景颜色,最重要的是,部分标题覆盖每个部分的顶部单元格,而不是位于其上方。这是相关代码:
// MARK: TableView delegates
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let sections = fetchedResultsController!.sections {
return sections.count
}
return 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections = fetchedResultsController!.sections {
let currentSection = sections[section]
return currentSection.numberOfObjects
}
return 0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 30))
let textHeader = UILabel(frame: CGRectMake(11, 0, 320, 20))
switch (section) {
case 0:
headerView.backgroundColor = UIColor.greenColor()
case 1:
headerView.backgroundColor = UIColor.blueColor()
case 2:
headerView.backgroundColor = UIColor.redColor()
case 3:
headerView.backgroundColor = UIColor.purpleColor()
default:
break
}
let hText: String = "\(fetchedResultsController!.sections![section].name)"
let hItems: String = "\((fetchedResultsController!.sections![section].numberOfObjects) - 1)"
let headerText: String = "\(hText) - \(hItems)items"
textHeader.text = headerText
textHeader.textColor = UIColor.whiteColor()
textHeader.backgroundColor = UIColor.clearColor()
headerView.addSubview(textHeader)
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat? {
return 20.0
}