如何向 TableView 部分添加左边距 Headers?

How to Add a Left Margin to TableView Section Headers?

我想在我的 TableView 部分 Headers 中添加左边距(即左边缘和部分 header 之间的 space)。

我在 headers 部分添加了以下内容:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let label = UILabel()
    label.backgroundColor = UIColor.white
    switch section {
    case 0:
        label.text = "Section Header 1"
    case 1:
        label.text = "Section Header 2"
    case 2:
        label.text = "Section Header 3"
    case 3:
        label.text = "Section Header 4"
    default:
        label.text = nil
    }
    return label
}

我添加了一个 .contentInset 来在其他组件中实现类似的功能,但我认为这在此处不起作用。有什么我可以添加到 label 属性 来实现左边距的吗?

使用一个额外的视图并调整框架。

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let sectionView = UIView()
    let label = UILabel(frame: CGRect(x: 20, y: 0, width: tableView.bounds.width - (20 * 2), height: sectionView.bounds.height))
    label.backgroundColor = UIColor.white
    switch section {
    case 0:
        label.text = "Section Header 1"
    case 1:
        label.text = "Section Header 2"
    case 2:
        label.text = "Section Header 3"
    case 3:
        label.text = "Section Header 4"
    default:
        label.text = nil
    }
    
    sectionView.addSubview(label)
    return sectionView
}

调整缩进,无额外视图

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let label = UILabel()
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.firstLineHeadIndent = 20
    let content: String
    switch section {
    case 0:
        content = "Section Header 1"
    case 1:
        content = "Section Header 2"
    case 2:
        content = "Section Header 3"
    case 3:
        content = "Section Header 4"
    default:
        content = ""
    }
    let attributedString = NSAttributedString(string: content, attributes: [.paragraphStyle : paragraphStyle, .backgroundColor: UIColor.white])
    label.attributedText = attributedString
    return label
}