如何在UITableViewCell之间添加间距

有什么办法可以在UITableViewCell之间添加空格吗?

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

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

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

或者可以这样说,图像的高度是例如50,并且我想在图像之间增加20个间距。 有什么办法可以做到这一点?

实现在单元格之间添加间距的方法是使numberOfSections =“您的数组数”,并使每个部分只包含一行。 然后定义headerView和它的高度。

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return yourArry.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return cellSpacingHeight; } -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *v = [UIView new]; [v setBackgroundColor:[UIColor clearColor]]; return v; } 

Swift版本

更新了Swift 3

为了未来的观众,这个答案比原来的问题更普遍一些。 这是Swift的基本UITableView示例的补充示例。

在这里输入图像描述

概观

基本的想法是为每个数组项目创build一个新的部分(而不是一个新的行)。 然后可以使用部分标题高度来分隔部分。

怎么做

  • 按照Swift的UITableView示例中所述设置您的项目。 (也就是说,添加一个UITableView并将tableView出口连接到View Controller)。

  • 在界面生成器中,将主视图背景颜色更改为浅蓝色,并将UITableView背景颜色清除。

  • 用下面的代码replaceViewController.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.row来获取数组元素和抽头位置的正确值。

你是怎么得到左边和右边的额外的填充/空间?

我知道你把空格添加到任何视图。 我使用了自动布局约束。 只需使用Interface Builder中的引脚工具即可为引导和尾随约束添加间距。

我需要做相同的概念,让UITableCell在它们之间有一个“空间”。 既然你不能从字面上增加单元格之间的空间,你可以通过操纵UITableView的单元格高度,然后在你的单元格的contentView中添加一个UIView来伪装它。 这是我在模拟这个时在另一个testing项目中做的一个原型的屏幕截图:

UITableViewCells之间的间距

这里是一些代码(注意:有很多硬编码值用于演示目的)

首先,我需要设置heightForRowAtIndexPath以允许UITableViewCell上的高度不同。

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *text = [self.newsArray objectAtIndex:[indexPath row]]; if ([text isEqual:@"December 2012"]) { return 25.0; } return 80.0; } 

接下来,我想操纵UITableViewCells的外观,所以我在willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath中为这个willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath做了这个willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath方法。

 - (void)tableView:(UITableView *)tableView willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (cell.IsMonth) { UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 20, 20)]; av.backgroundColor = [UIColor clearColor]; av.opaque = NO; av.image = [UIImage imageNamed:@"month-bar-bkgd.png"]; UILabel *monthTextLabel = [[UILabel alloc] init]; CGFloat font = 11.0f; monthTextLabel.font = [BVFont HelveticaNeue:&font]; cell.backgroundView = av; cell.textLabel.font = [BVFont HelveticaNeue:&font]; cell.textLabel.textColor = [BVFont WebGrey]; } if (indexPath.row != 0) { cell.contentView.backgroundColor = [UIColor clearColor]; UIView *whiteRoundedCornerView = [[UIView alloc] initWithFrame:CGRectMake(10,10,300,70)]; whiteRoundedCornerView.backgroundColor = [UIColor whiteColor]; whiteRoundedCornerView.layer.masksToBounds = NO; whiteRoundedCornerView.layer.cornerRadius = 3.0; whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(-1, 1); whiteRoundedCornerView.layer.shadowOpacity = 0.5; [cell.contentView addSubview:whiteRoundedCornerView]; [cell.contentView sendSubviewToBack:whiteRoundedCornerView]; } } 

请注意,我做了我的whiteRoundedCornerView高度70.0,这是什么原因造成的模拟空间,因为单元格的高度实际上是80.0,但我的contentView是70.0,使它的外观。

可能还有其他方法可以更好地完成这个任务,但这只是我如何去做到的。 我希望它可以帮助别人。

我使用Swift的简单解决scheme:

 // Inside UITableViewCell subclass override func layoutSubviews() { super.layoutSubviews() let f = contentView.frame let fr = UIEdgeInsetsInsetRect(f, UIEdgeInsetsMake(10, 10, 10, 10)) contentView.frame = fr } 

一行代码

 override func layoutSubviews() { super.layoutSubviews() contentView.frame = UIEdgeInsetsInsetRect(contentView.frame, UIEdgeInsetsMake(10, 10, 10, 10)) } 

结果 在这里输入图像描述

您将不得不将帧设置到您的图像。 未经testing的代码是

 cell.imageView.frame = CGRectOffset(cell.frame, 10, 10); 

如果您尚未使用节标题(或页脚),则可以使用它们为表格单元添加任意间距。 而不是有一个n行的部分,创build一个表与n个部分各有一行。

实现tableView:heightForHeaderInSection:方法来控制间距。

你也可能想要实现tableView:viewForHeaderInSection:来控制间距的样子。

我能想到的三种方法:

  1. 创build一个自定义表格单元格,以您希望的方式展示整个单元格的视图

  2. 除了将图像添加到图像视图,清除图像视图的子视图,创build一个自定义视图,为图像和另一个视图添加UIImageView,也许是一个简单的UIView,提供所需的间距,并将其添加为子视图图像视图。

  3. 我想build议你直接操纵UIImageView来设置一个固定的大小/填充,但我没有靠近Xcode,所以我不能确认是否/如何工作。

那有意义吗?

我认为最直接的解决scheme,如果你只是寻找一个小空间,可能最便宜的是简单地设置单元格边框颜色到您的表背景颜色,然后设置边框宽度,以获得所需的结果!

  cell.layer.borderColor = blueColor.CGColor cell.layer.borderWidth = 3 

是的,您可以通过在cell中的内容视图上创build一个基本视图来增加或减less两个单元格之间的间距(填充)。为内容视图背景设置清晰的颜色,并且可以调整基本视图的高度以在单元格之间创build空间。

试试看 – (UIEdgeInsets)layoutMargins; 在细胞上

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

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

使用UITableViewDelegate, heightForRowAtIndexPath并返回行的高度。

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

在swift中的示例3 ..

在这里输入图像描述

  1. 折叠单个视图应用程序
  2. 在视图控制器中添加tableview
  3. 为tablview单元格添加一个自定义单元
  4. 视图控制器代码如下所示

      class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var arraytable = [[String:Any]]() override func viewDidLoad() { super.viewDidLoad() arraytable = [ ["title":"About Us","detail":"RA-InfoTech Ltd -A Joint Venture IT Company formed by Bank Asia Ltd"], ["title":"Contact","detail":"Bengal Center (4th & 6th Floor), 28, Topkhana Road, Dhaka - 1000, Bangladesh"] ] tableView.delegate = self tableView.dataSource = self //For Auto Resize Table View Cell; tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension //Detault Background clear tableView.backgroundColor = UIColor.clear } 

    func numberOfSections(在tableView:UITableView) – > Int {return arraytable.count}

      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } // Set the spacing between sections func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } // Make the background color show through func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = UIColor.clear return headerView } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! CustomCell cell.tv_title.text = arraytable[indexPath.section]["title"] as! String? cell.tv_details.text = arraytable[indexPath.section]["detail"] as! String? //label height dynamically increase cell.tv_details.numberOfLines = 0 //For bottom border to tv_title; let frame = cell.tv_title.frame let bottomLayer = CALayer() bottomLayer.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width, height: 1) bottomLayer.backgroundColor = UIColor.black.cgColor cell.tv_title.layer.addSublayer(bottomLayer) //borderColor,borderWidth, cornerRadius cell.backgroundColor = UIColor.lightGray cell.layer.borderColor = UIColor.red.cgColor cell.layer.borderWidth = 1 cell.layer.cornerRadius = 8 cell.clipsToBounds = true return cell } } 
  5. 下载完整源代码到Github:链接

    https://github.com/enamul95/CustomSectionTable

我的情况是我用自定义的UIView viewForHeader节也heightForHeader节返回常量高度说40,问题是当没有数据时,所有的头部视图互相触及。 所以我想在没有数据的部分之间的空间,所以我通过改变“桌面风格”飞机固定到“组”,它为我工作。

添加一个内部视图的单元格,然后添加自己的意见。