【问题标题】:Add offset to UITableViewCell at time of creation?在创建时向 UITableViewCell 添加偏移量?
【发布时间】:2017-04-04 04:20:55
【问题描述】:

我正在努力以这种方式在cellForRowAtIndexPath 中加载一个单元格,这样我就可以只为一个单元格提供自定义偏移量 - 在我的情况下,仅限于第 1 节的单元格 1。我想给一个自定义偏移到单元格,因为相同的单元格 (xib) 用于项目的其他部分,它延伸到表格的边缘而没有任何偏移。我所有的单元格都设计为 *.xib 文件。如果需要,我愿意在awakeFromNib() 或其他方法中设置一些内容。

有没有办法在创建或加载单元格时设置单元格偏移、插入、边距、填充(不确定措辞是否正确)?

我试过用这种方式设置边距,但不起作用:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.section == 0) && (indexPath.row) == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCell
        cell.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10)
        return cell
    }
} else {
    // Load other cells
}

【问题讨论】:

  • 看起来您想使用节标题。
  • @shallowThought 有趣的想法。你能扩大一点吗?我已经实现了viewForHeaderInSection,我在其中返回MyCell(),它是UITableViewCell 的子类,但它不起作用。我得到的只是一个空标题。有什么想法可能是错的吗?
  • 您的标头必须是UITableViewHeaderFooterView 的子类。更多信息在这里:developer.apple.com/reference/uikit/uitableviewheaderfooterview

标签: ios swift uitableview layout


【解决方案1】:

我认为您的 cellForRowAtIndexPath 实现已经很接近了。尝试将边距应用于单元格的 contentView(单元格内容的超级视图和单元格的子视图)。您可能还需要将单元格的背景颜色设置为清除(contentView 仍为白色)。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.section == 0) && (indexPath.row) == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCell
        cell.contentView.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10)
        return cell
    }
} else {
    // Load other cells
}

【讨论】:

  • 感谢@Mark 我已经实现了cell.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10)cell.contentView.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10)cell.backgroundColor = UIColor.clear 的所有组合,但单元格仍然扩展到边缘。有什么想法吗?
  • 表格视图可能会覆盖您的layoutMargins。在contentView 上设置layoutMargins 会插入您的内容(如果您将其锚定到边缘),但您的contentView 本身不会改变。您可以将子视图添加到您的contentView(以包含所有标签等),将其锚定到contentView 的边缘,并将contentView 的背景颜色设置为清除。然后您就可以设置contentView 的layoutMargins。
猜你喜欢
  • 2011-07-25
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多