【问题标题】:How to Add a Left Margin to TableView Section Headers?如何为 TableView 节标题添加左边距?
【发布时间】:2021-04-29 21:05:00
【问题描述】:

我想为我的 TableView 节标题添加左边距(即左边缘和节标题之间的空间)。

我正在添加具有以下内容的部分标题:

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 属性来实现左边距的吗?

【问题讨论】:

  • 您是通过编程方式还是通过界面生成器进行操作,因为答案会在此基础上加深。
  • 也许这会有所帮助:var spacer = " " 并在创建标签实例后立即添加此间隔。

标签: ios swift uitableview tableview


【解决方案1】:

调整缩进,没有多余的视图

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
}

【讨论】:

  • 感谢您的指导。超级有用!
【解决方案2】:

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

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
}

【讨论】:

  • 将标签的高度设置为 sectionView.bounds.height 对我不起作用,因为当时高度为零。我必须将高度设置为固定值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 2022-09-30
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 2020-01-05
相关资源
最近更新 更多