【问题标题】:Adding Spacing Between Basic Table View Cells在基本表格视图单元格之间添加间距
【发布时间】:2017-02-21 14:20:12
【问题描述】:

我有基本的表格视图单元格,我想在它们之间设置一些间距。

我试过了

cell.contentView.layoutMargins.top = 8

cell.layoutMargins.top = 8 

但这没有用。我知道我可以创建一个自定义单元格,但我想知道如何以这种方式添加边距。

编辑:

然后我将单元格样式更改为自定义:

并添加了一个视图,以便我可以对其设置一些约束

但结果还是一样,单元格之间没有间距,而且它有点忽略了自定义视图,我猜是因为它需要一个单元格的自定义类,但我不想这样做。

【问题讨论】:

  • 只需创建包含单元格视图+额外空间视图(与背景颜色相同)的单元格,然后它看起来就像单元格之间的间距
  • 对我来说最简单快捷的方法是在底部添加自定义视图

标签: ios swift uitableview


【解决方案1】:

您不应在单元格本身之间添加间距,而应将自定义 containerView 添加到单元格的 contentView 并带有顶部和/或底部约束。

【讨论】:

  • 这听起来不错,但它给出了一个错误,即无法将容器视图放置在运行时重复的视图中。然后,我将单元格配置从 Basic 更改为 Custom,我在 Content View 中添加了一个视图并使用了约束,但它没有任何效果。
  • @fullMoon 请将您的布局添加到问题中,以便我找到问题所在。
【解决方案2】:

请试一试 您可以在两个单元格之间创建标题并添加空格

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return array.count
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return 1 // Because we need to space between two cell
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    //Configure your cell

    let cel:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
    cel.textLabel?.text = array[indexPath.section] //please use section because we have only one row for all section
    return cel
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
    return 15 // whatever you want space between two cell
}

【讨论】:

    【解决方案3】:

    您实现在单元格之间添加间距是使 numberOfSections = array.count 并使每个部分仅包含一行。然后定义 headerView 及其高度。

     func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return cellSpacingHeight
        }
    

    【讨论】:

    • 这是一种解决方法,但不要这样做。表格视图部分用于其他目的。当你遵循这个建议时,你会发现自己处于一个尴尬的境地,并且在以后的某个时候真的需要将一些单元格分成几个部分
    【解决方案4】:

    如果您只有一个部分,请尝试交换部分中的行数和 tableView 中的部分数。然后,您可以使用委托:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 10
        }
    

    【讨论】:

      【解决方案5】:

      一般来说,使用UITableViewCell 或其contentViewlayoutMargins 很容易出错。以我的经验,单元格的layoutMarginscontentView 在表格重新加载期间的几个点都会重置。有两种解决方法:

      1. 使用间距单元格。例如,只需创建一个透明的 UITableViewCell 子类,该子类在 contentView 上设置了特定的高度约束。
      2. 使用透明的UITableViewCell 子类,并将您自己的(可能是不透明的)子视图添加到contentView 并将顶部/底部约束设置为所需间距的1/2。您可以覆盖setHighlighted:animated 以控制单元格在选择时的外观。这是我在屏幕截图中使用的方法。它也适用于在左/右添加边距。

      【讨论】:

        猜你喜欢
        • 2018-07-30
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多