【发布时间】:2016-04-29 09:08:38
【问题描述】:
在之前使用 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
}
【问题讨论】:
-
请使用 imgur.com 网站添加相关截图
-
抱歉,我无法再访问该项目,但它只是一个全宽的标题,20 高,有不同的颜色,看起来像是部分之间的分隔线。它位于每个部分的第一个单元格之上,并且从未像在这个新的 Swift 代码中那样覆盖它。
标签: ios iphone swift uitableview uitableviewsectionheader