ios - 如何在 Swift 中调整 TableView 标题的缩进?

标签 ios swift uitableview tableview

我知道如何设置标题文本并对其进行样式设置,但在我的一生中,我找不到任何解释如何调整文本缩进的内容。这是我尝试过的:

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
}

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

Unable to activate constraints because they have no common ancestor.

这让我对我的计算机说,“如果 header.textLabel 让我到达 UILabel,并且 header 是确实是一个 UITableViewHeaderFooterView,我想你应该知道一个是另一个的祖先!”

最佳答案

您可以通过首先为整个 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

}

关于ios - 如何在 Swift 中调整 TableView 标题的缩进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43132547/

相关文章:

ios - 使用 Storyboard引用

ios - 如何修复约束不显示重复的单词?

ios - 如何在 ios Swift 语言的 uiimageview 中设置动画和填充颜色?

ios - 更改 tableView 中先前单元格的属性

ios - UILabel 文本使用 NSTimer 更新,但在触摸/拖动 UITableView 时不更新(gif 示例)

iphone - 为 uitableview 创建自定义删除按钮

objective-c - Cocos2d移动节点断断续续

ios - 我想从一个字符串数组创建一个字符串数组的多维数组

swift - 如何在用户单击按钮时使图像更改几秒钟,然后 swift 恢复为原始图像?

Swift - 使用自定义过滤器返回 tableView 中的数组数据