【问题标题】:How to adjust the indent of the header of a TableView in Swift?如何在 Swift 中调整 TableView 标题的缩进?
【发布时间】:2023-03-30 14:49:01
【问题描述】:

我知道如何设置标题文本和样式,但是对于我的生活,我找不到任何解释如何调整文本缩进的东西。这是我尝试过的:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.translatesAutoresizingMaskIntoConstraints = false
    header.textLabel?.leftAnchor.constraint(equalTo: header.leftAnchor, constant: 15).isActive = true
}

上面的代码(以及我尝试过的每个变体)都会导致错误:

无法激活约束,因为它们没有共同的祖先。

这让我对我的电脑说,“如果header.textLabel 让我进入UILabel,而header 确实是UITableViewHeaderFooterView,我想你应该知道一个是祖先另一个!”

【问题讨论】:

    标签: ios swift uitableview tableview


    【解决方案1】:

    您可以通过首先为整个TableView 设置separatorInset 来做到这一点,如下所示:

    let headerInset: CGFloat = 50
    tableView.separatorInset = UIEdgeInsets.init(top: 0, left: headerInset, bottom: 0, right: 0)
    

    那么如果你想将表格的单元格定位到与TableView的边缘对齐,你可以在forRowAt indexPath方法中做到这一点:

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
        cell.separatorInset = UIEdgeInsets.zero
    
    }
    

    【讨论】:

    • 这首先是有效的,但是当你推送到另一个视图控制器,然后用 tableview 回到屏幕时,插图丢失了——即使在 viewdidappear 中设置了分隔符插图,插图不见了。
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2019-04-17
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多