UITableViewCells swift3之间的间距

Ank*_*wat 5 cellspacing uitableview ios swift3

我正在swift创建一个IOS应用程序,并希望像这样在单元格之间添加间距

在此输入图像描述

我想给每个表视图单元格的空间与我的附加图像相同.我怎么能这样做?现在所有细胞都没有任何空间.swift3

小智 9

你可以在你的tableView单元格中尝试这个:

class cell: UITableViewCell{
override var frame: CGRect {
    get {
        return super.frame
    }
    set (newFrame) {
        var frame =  newFrame
        frame.origin.y += 4
        frame.size.height -= 2 * 5
        super.frame = frame
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


dah*_*boy 5

  1. 在 Storyboard 中,您的视图层次结构应该是这样的。View CellContent(突出显示)将包含所有组件。

在此处输入图片说明

  1. View CellContent从其父视图的顶部、底部、前导和尾随设置 10 像素的边距。

  2. 现在,选择tblCell并更改背景颜色。

在此处输入图片说明

在此处输入图片说明

  1. 现在运行你的项目,确保委托和数据源被正确绑定。

输出

在此处输入图片说明

注意:我只是为了虚拟目的添加了 1UILabel英寸View CellContent


Gul*_*han 5

更新:现在可以替换UIEdgeInsetsInsetRect方法,您可以这样

contentView.frame = contentView.frame.inset(by: margins)
Run Code Online (Sandbox Code Playgroud)

斯威夫特4答案:

在您的自定义单元格类中添加此功能

override func layoutSubviews() {
    super.layoutSubviews()
    //set the values for top,left,bottom,right margins
            let margins = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
    contentView.frame = UIEdgeInsetsInsetRect(contentView.frame, margins)
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要更改值

*****注意*****调用超级功能

super.layoutSubviews()
Run Code Online (Sandbox Code Playgroud)

非常重要,否则您会遇到奇怪的问题


234*_*Shk 2

一种简单的方法是集合视图而不是表视图,并为集合视图提供单元格间距并使用

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
    let widthSize = collectionView.frame.size.width / 1
    return CGSize(width: widthSize-2, height: widthSize+20)
}
Run Code Online (Sandbox Code Playgroud)

如果您只需要表格视图,则将背景视图添加为容器视图,并将背景颜色设置为白色,单元格背景颜色设置为透明颜色,将单元格前导、颤音、底部的背景视图设置为 10

backgroundView.layer.cornerRadius = 2.0
backgroundView.layer.masksToBounds = false
backgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
Run Code Online (Sandbox Code Playgroud)