有没有办法增加UITableViewCell之间的间距?

我已经创建了一个表,每个单元格只包含一个图像。图像被这样分配给单元格:

cell.imageView.image = [myImages objectAtIndex:indexPath.row];

但这使得图像放大并适合整个细胞,并且图像之间没有间隔。

或者让我们这样说,图像的高度是50,我想在图像之间增加20的间距。有什么办法可以做到吗?


当前回答

只是把对我有用的答案添加到答案池中。

我已经在TableViewCell中添加了一个视图(紫色视图),我使用它作为单元格的内容视图。并限制紫色视图在顶部和底部都有填充,或者其他你想要的,但我认为这种方式创造了更多的灵活性。

其他回答

斯威夫特版本

Swift 3更新

为了方便以后的观众,这个答案比原来的问题更一般。它是Swift基本UITableView示例的补充示例。

概述

基本思想是为每个数组项创建一个新节(而不是新行)。然后,可以使用节头高度对节进行间隔。

怎么做

按照UITableView示例中的描述设置你的项目。(也就是说,添加一个UITableView并将tableView outlet连接到视图控制器)。 在Interface Builder中,将主视图背景颜色更改为浅蓝色,并将UITableView背景颜色更改为clear。 用以下代码替换ViewController.swift代码。

ViewController.swift

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    
    let cellReuseIdentifier = "cell"
    let cellSpacingHeight: CGFloat = 5
    
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // These tasks can also be done in IB if you prefer.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // MARK: - Table View delegate methods
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.animals.count
    }
    
    // There is just one row in every section
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    // Set the spacing between sections
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return cellSpacingHeight
    }
    
    // Make the background color show through
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.clear
        return headerView
    }
    
    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        
        // note that indexPath.section is used rather than indexPath.row
        cell.textLabel?.text = self.animals[indexPath.section]
        
        // add border and color
        cell.backgroundColor = UIColor.white
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8
        cell.clipsToBounds = true
        
        return cell
    }
    
    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // note that indexPath.section is used rather than indexPath.row
        print("You tapped cell number \(indexPath.section).")
    }
}

注意indexPath。section而不是indexPath。行,以获得数组元素的正确值和点击位置。

你是如何在右边和左边得到额外的填充/空间的?

我得到它的方法和你给任何视图加空格的方法是一样的。我使用了自动布局约束。只需使用接口构建器中的引脚工具为开头和结尾约束添加间距。

这是实际的解决方案

使用节而不是行因为每一行都有一个节所以你可以给页眉留出空间节脚这是代码,把它粘贴到你的视图控制器类中,在这里你创建tableview outlet

如果你想要顶部间距使用heightForHeaderInSection 如果你想要底部间距,只需使用heightForFooterInSection如下所示

复制粘贴即可

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

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let v = UIView()
    v.backgroundColor = UIColor.clear
    return v
}

    func numberOfSections(in tableView: UITableView) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

使用UITableViewDelegate, highightforrowatindexpath并返回行高。

 (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 return 100.0f ;
}

不需要使用一堆不同的部分。其他的答案使用框架insets和CGRect和图层…等等等等。不太好;使用自动布局和自定义UITableViewCell。在那个UITableViewCell中,不是在contentView中查看你的内容,而是创建一个新的containerView(一个UIView),在contentView中查看容器视图,然后在容器视图中查看所有视图。

现在要创建空格,只需编辑容器视图的布局边距,如下所示:

class CustomTableViewCell: UITableViewCell {
    let containerView = UIView()
    let imageView = UIImageView()

    required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        containerView.translatesAutoResizingMaskIntoConstraints = false
        imageView.translatesAutoResizingMaskIntoConstraints = false
        contentView.addSubview(containerView)
        containerView.addSubview(imageView)

        contentView.layoutMargins = UIEdgeInsets(top: 15, left: 3, bottom: 15, right: 3)
        containerView.layoutMargins = UIEdgeInsets(top: 15, left: 17, bottom: 15, right: 17) // It isn't really necessary unless you've got an extremely complex table view cell. Otherwise, you could just write e.g. containerView.topAnchor

        let cg = contentView.layoutMarginsGuide
        let lg = containerView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: cg.topAnchor),
            containerView.leadingAnchor.constraint(equalTo: cg.leadingAnchor),
            containerView.trailingAnchor.constraint(equalTo: cg.trailingAnchor),
            containerView.bottomAnchor.constraint(equalTo: cg.bottomAnchor),
            imageView.topAnchor.constraint(equalTo: lg.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: lg.bottomAnchor)
        ])
    }
}

我认为这是最干净的解决方案:

class MyTableViewCell: UITableViewCell {
    override func awakeFromNib() {
        super.awakeFromNib()
        layoutMargins = UIEdgeInsetsMake(8, 0, 8, 0)
    }
}