【问题标题】:adding some margin below section header text of a UITableView在 UITableView 的部分标题文本下方添加一些边距
【发布时间】:2016-05-23 03:55:03
【问题描述】:

我已经设置了标题文本的样式:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? TableViewCell

    cell!.titleLabel!.text = sections[indexPath.section].objects[indexPath.row].name
    cell!.datetimeLabel!.text = "on " + sections[indexPath.section].objects[indexPath.row].date

    return cell!
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
   return 100
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].heading // Open Events
}

我想在表格单元格部分开始之前在其下方添加一些边距/填充。我用heightForHeaderInSection 添加了一些边距/填充顶部。有什么方法可以添加一些顶部/底部边距/填充?

【问题讨论】:

  • 你能不能不让标题高度更大,把“开放事件”标签上移?
  • 将 heightForHeaderInSection 设为 120 并尝试。
  • @Fonix "open events" 不是标签,而是我刚刚在代码中添加的函数tableView(tableView: UITableView, titleForHeaderInSection section: Int) 中设置的部分标题
  • @Signare 将其设置为 120 只会增加顶部间距,而没有任何底部间距
  • 创建一个标签并将其添加到单元格中。因此您可以设置该标签的顶部间距。

标签: ios swift uitableview


【解决方案1】:

titleForHeaderInSection 方法将具有默认的节标题框架。您可以使用viewForHeaderInSection 方法对其进行自定义。试试这个代码:

  override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerFrame = tableView.frame

    let title = UILabel()
    title.frame =  CGRectMake(10, 10, headerFrame.size.width-20, 20) //width equals to parent view with 10 left and right margin
    title.font = title.font.fontWithSize(14)
    title.text = self.tableView(tableView, titleForHeaderInSection: section) //This will take title of section from 'titleForHeaderInSection' method or you can write directly
    title.textColor = UIColor.blueColor()

    let headerView:UIView = UIView(frame: CGRectMake(0, 0, headerFrame.size.width, headerFrame.size.height))
    headerView.addSubview(title)

    return headerView
}

希望这对你有用。

【讨论】:

  • 谢谢,是的,现在只需稍加调整即可使用 gist.github.com/sayanee/a164f7f22423c17494e6。我想知道CGRectMake 的第三个宽度参数是否可以动态获取父宽度。
  • 这里是截图,如果你想更新dropbox.com/s/ook1ymq6jglsa0o/…
  • 您的意思是,您希望标题标签的高度与 headerView 的高度相同?
  • 哎呀,我的意思是标签的宽度与节标题的宽度(不是高度)相同
  • 谢谢 :) 现在一切都好!如果需要,您可以使用图片的 Dropbox 链接和更新代码的要点。
【解决方案2】:

使用viewForHeaderInSection: 并返回一个带有标签的视图,其下方具有正确的间距,而不是使用titleForHeaderInSection 中的默认标题

请参阅this answer 了解示例

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2021-04-06
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多