Заголовки раздела UITableView перекрывают UITableviewCell и не имеют цвета фона

В предыдущем проекте, использующем 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
}

2 ответа

Заголовок накладывается, потому что его высота равна 30, а вы возвращаете только 20,0 в heightForHeaderInSection FUNC. цвет фона не отображается, потому что вы пропустите break для каждого "случая" в операторах switch.

Случаи переключения должны заканчиваться перерывом, тогда только он вернет 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
}
Другие вопросы по тегам