在UITableView的节标题文本下添加一些边距

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

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添加了一些margin / padding top。 有什么方法可以添加一些上/下边距/填充?

在此处输入图像描述

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 } 

希望这对你有用。

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

看一下这个答案的例子