1

在之前使用 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
}
4

2 回答 2

3

标题覆盖,因为它的高度是 30,而你在heightForHeaderInSectionfunc 中只返回 20.0。背景颜色没有显示,因为您错过了breakswitch 语句中的每个“案例”。

于 2016-04-29T09:29:34.337 回答
0

switch case 应该以 break 结束,然后只有它会返回 backgroundcolor

检查下面的代码

switch (section) {
case 0:
    headerView.backgroundColor = UIColor.greenColor()
    break
case 1:
    headerView.backgroundColor = UIColor.blueColor()
    break
case 2:
    headerView.backgroundColor = UIColor.redColor()
    break
case 3:
    headerView.backgroundColor = UIColor.purpleColor()
    break
default:
    break
}
于 2016-04-29T09:34:32.377 回答