如何实现让 UITableView 设置其单元格的插图而不在整个表格上设置插图? [英] How can I achieve having an UITableView set the insets of its cells without setting the inset on the entire table?

查看:13
本文介绍了如何实现让 UITableView 设置其单元格的插图而不在整个表格上设置插图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITableViewCell 的内容延伸到它的所有边缘.我在需要不同插图的多个表格中使用此单元格.(即,一张表将从左侧插入 8 点,另一张表将插入 20 点.我想缩进父 UITableView 代码中的单元格(可能是 cellForRow?) 而不缩进整个表格.

I have a UITableViewCell with content that extends to all of its edges. I use this cell in multiple tables with where it needs varying insets. (i.e. one table will have it inset from the left by 8 points, another will have it inset 20 points. I'd like to indent the cell in the parent UITableView code (maybe cellForRow?) without indenting the entire table.

这显然是为整个表格设置的,但我想根据需要逐个单元地进行设置:

This obviously sets it for the entire table, but I'd like to do it on a cell-by-cell basis as needed:

tableView.contentInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: -20)

这没有效果:

tableViewCell.contentView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: -20)

这也不起作用(即使它在单元格本身上):

Nor is this working (even though it's on the cell itself):

override func layoutMarginsDidChange() {
    super.layoutMarginsDidChange()

    self.layoutMargins = UIEdgeInsets(top: 0, left: 20 bottom: 0, right: -20)
}

推荐答案

确保在 xib/storyboard 中限制边距.然后在 UITableViewCell 上设置以下内容:

Make sure you constrain to margins in the xib/storyboard. Then set the following on the UITableViewCell:

var topInset: CGFloat = 0
var leftInset: CGFloat = 0
var bottomInset: CGFloat = 0
var rightInset: CGFloat = 0

override func layoutMarginsDidChange() {
    super.layoutMarginsDidChange()
    self.layoutMargins = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}

然后在tableView的cellForRowAt中,使用如下:

Then in the tableView cellForRowAt, use the following:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let browseTableViewCell = tableView.dequeueReusableCell(withIdentifier: "BrowseTableViewCell", for: indexPath) as! BrowseTableViewCell

    browseTableViewCell.leftInset = 20
    browseTableViewCell.rightInset = 20
    // Top and bottom insets are not needed. They will default to 0.

    return browseTableViewCell
}

这篇关于如何实现让 UITableView 设置其单元格的插图而不在整个表格上设置插图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆