【问题标题】:UITableView section headers overlapping UITableviewCell and have no background colourUITableView 部分标题与 UITableviewCell 重叠并且没有背景颜色
【发布时间】: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


【解决方案1】:

标题重叠,因为它的高度是 30,而您在 heightForHeaderInSection func 中只返回 20.0。背景颜色没有显示,因为您错过了 switch 语句中每个“case”的break

【讨论】:

  • 在发布前我已经尝试过所有标题大小不超过 45,包括 30,但并没有解决问题。
  • 那么表格视图是什么样子的?
【解决方案2】:

switch case应该以break结尾,然后才会返回背景色

检查下面的代码

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
}

【讨论】:

  • 虽然这在 Objective C 中是正确的,但在 Swift 中,您不再在每种情况下都包含 break 语句,除非您不想为特定情况执行任何语句。
猜你喜欢
  • 2019-03-13
  • 2021-09-22
  • 2023-03-04
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 2015-07-26
相关资源
最近更新 更多