adding some margin below section header text of a UITableView

南笙酒味 提交于 2020-02-02 06:50:07

问题


I have styled the header text:

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
}

And I would like to add some margin / padding below it before the section of the table cells start. I have added some margin / padding top with heightForHeaderInSection. Any way to add some top / bottom margin / padding?


回答1:


titleForHeaderInSection method will have the default section header frame. You can use viewForHeaderInSection method to customize it. Try this code :

  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
}

Hope this will work for you.




回答2:


use viewForHeaderInSection: and return a view with a label with the correct spacing below it instead of using the default header in titleForHeaderInSection

see this answer for an example



来源:https://stackoverflow.com/questions/35355156/adding-some-margin-below-section-header-text-of-a-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!