【问题标题】:How to add spacing between UITableViewCell如何在 UITableViewCell 之间添加间距
【发布时间】:2011-09-07 04:38:07
【问题描述】:

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

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

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

但这会使图像放大并适合整个单元格,并且图像之间没有间距。

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

【问题讨论】:

  • 对于 Swift 2.2 在这里查看我的答案:stackoverflow.com/a/37673417/2696626
  • 真正单元格之间添加间距的唯一方法非常简单。有第二个单元格,它是一个垫片。如果你有(比如说)10 个真正的细胞,实际上有 19 个细胞,所以 10 个细胞之间有 9 个垫片。这真的很容易。就一行代码。

标签: ios objective-c uitableview


【解决方案1】:

您必须为图像设置框架。未经测试的代码是

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

【讨论】:

  • 刚刚用 backgroundView 测试过,这是最简单的工作解决方案
  • 如果您要继承 UITableViewCell,请确保在 layoutSubviews 中调用此代码
  • @NicoHämäläinen 好吧,在过去三年中,我开发了 20 多个应用程序,我总是将 UITableViewCell 子类化以获得我需要的结果 :) ... 子类化 UITableViewCell 是很常见。
  • @NicoHämäläinen 继承 UITableViewCell 没有任何问题。当您创建自定义 UITableViewCells 时,您应该继承 UITableViewCell
  • @NicoHämäläinen 你应该更新你的评论。人们倾向于获取信息而不是进一步阅读。由于这个网站是一个很好的资源,开发人员倾向于相信他们在这里看到的事实,这可能会误导他们思考可怕的事情......只是我的两枚硬币。也许我歇斯底里
【解决方案2】:

我能想到的三种方法:

  1. 创建一个自定义表格单元格,以您希望的方式布置整个单元格的视图

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

  3. 我想建议您直接操作 UIImageView 以设置固定大小/填充,但我离 Xcode 还很远,所以我无法确认这是否/如何工作。

这有意义吗?

【讨论】:

    【解决方案3】:

    如果您还没有使用节页眉(或页脚),您可以使用它们为表格单元格添加任意间距。与其让一个部分有 n 行,不如创建一个表,其中有 n 个部分,每个部分有一行。

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

    您可能还想实现tableView:viewForHeaderInSection: 来控制间距。

    【讨论】:

      【解决方案4】:

      我需要做同样的概念,让 UITableCells 在它们之间有一个“空间”。由于您不能从字面上添加单元格之间的空间,您可以通过操纵 UITableView 的单元格高度然后将 UIView 添加到单元格的 contentView 来伪造它。这是我在另一个测试项目中模拟时所做的原型的屏幕截图:

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

      首先,我需要设置 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 方法中执行此操作。

      - (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,这使它具有外观。

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

      【讨论】:

      • 仅供参考,对于大量单元格,您可能希望在单元格子类中设置内容视图,而不是 willDisplayCell。添加到队列中的单元越多,这样做的性能开始受到巨大影响
      • @BBH1023 来回导航以快速查看时,每次出现视图时,阴影层都会增加。如果它已经应用过一次,你会如何建议取消它
      • 禁止添加更多阴影:NSInteger tag = 120; if (indexPath.row != 0) { if (cell.tag != 120) { cell.contentView.backgroundColor = [UIColor clearColor]; ... [cell.contentView sendSubviewToBack:whiteRoundedCornerView]; cell.tag = 标签; } }
      【解决方案5】:

      我实现在单元格之间添加间距的方法是使 numberOfSections = "Your array count" 并使每个部分仅包含一行。然后定义 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;
      }
      

      【讨论】:

      • 这很好用。我不得不稍微更改 cellForRowAtIndexPath,而不是普通的数组 [indexPath.row] 而是数组 [indexPath.section]。否则它将在所有部分中显示数组的第一项。
      • @TomSpee - 你是如何在 cellForRowAtIndexPath 中解决这个问题的?
      • @TKutal - 就像 cellForRowAtIndexPath 中的正常代码一样,但将 indexPath.row 更改为 indexPath.section
      • 虽然这实现了提问者的愿望,但我不相信 Apple 会推荐这种方法。如果我错了,请纠正我,但我相信“部分”是为了在逻辑上分离您在表中表示的数据的“部分”。您不应该使用“节”来设置每个数据单元格之间的空格,否则这些单元格应该都显示在一个节中。我认为更好的方法,虽然更困难,是继承 UITableViewCell,并通过在单元格底部添加一个视图来模拟表格视图分隔符。
      • 那么 Apple 不应该抱怨,而是创建一种方便的方法来改变行之间的空间。
      【解决方案6】:

      向单元格添加内部视图,然后向其中添加您自己的视图。

      【讨论】:

        【解决方案7】:

        尝试调查 - (UIEdgeInsets)layoutMargins; 在细胞上

        【讨论】:

          【解决方案8】:

          斯威夫特版

          为 Swift 3 更新

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

          概述

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

          怎么做

          • 按照UITableView example for Swift 中的说明设置您的项目。 (即添加一个UITableView 并将tableView 插座连接到视图控制器)。

          • 在 Interface Builder 中,将主视图背景颜色更改为浅蓝色,并将 UITableView 背景颜色更改为清除。

          • 将 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.row 是为了获得数组元素和点击位置的正确值。

          您是如何获得左右两侧额外的填充/空间的?

          我得到它的方式与为任何视图添加间距相同。我使用了自动布局约束。只需在 Interface Builder 中使用 pin tool 为前导和尾随约束添加间距。

          【讨论】:

          • 嗨,我想知道如果不将所有行都转换为节,这是否可行。我在每个 tableViewCell 上都有边框,所以增加高度无济于事。我的单元格有很多自定义项,我不想将其转换为部分。谢谢!
          • @user2901306,起初我对使用这种方法犹豫不决,也是因为感觉我应该能够只使用行并增加边距或其他东西。但是,我没有找到一种方法来做到这一点,而且这种方法效果很好。您不必更改单元格上的自定义设置。您基本上只需要为行数添加numberOfSectionsInTableViewreturn 1。然后使用indexPath.section 获取当前单元格索引。试一次。我想您会发现您不需要对当前设置进行太多更改。这绝对比子类化容易。
          • 在 cellForRow 中使用 cell.layer.xxx 会给你的性能带来影响。最好在 XIB 中设置这些值
          • @Suragch - 在很多情况下,您已经有单独的部分,所以实际上您并没有改变单元格之间的间距 - 只是部分之间的间距。
          • @FateNuller,我不同意你的观点。 Husam's answer 看起来不错。
          【解决方案9】:

          我的情况是我在部分中使用自定义 UIView 来 viewForHeader 部分中的 heightForHeader 也返回恒定高度,比如 40,问题是当没有数据时所有标题视图都相互接触。所以我想在没有数据的部分之间留出空间,所以我通过将“tableview style”平面更改为“Group”来修复它。它对我有用。

          【讨论】:

            【解决方案10】:

            我使用 Swift 的简单解决方案:

            // Inside UITableViewCell subclass
            
            override func layoutSubviews() {
                super.layoutSubviews()
            
                contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
            }
            

            结果

            【讨论】:

            • 不错的解决方案。如果有人有问题,我必须先致电super.layoutSubviews(),以确保在设置框架之前正确布置整个视图。
            • @Husam 您的解决方案对我有用。但是我在选择单元格时遇到了问题。我已经为 contentView 设置了边框,每当我选择单元格时,边框都会变小。我该如何解决?
            • 嘿,胡萨姆。感谢您提供出色的解决方案。不要告诉我如何改变单元格之间添加内容的颜色?
            • 这是一个比公认答案更好的解决方案。公认的答案有近 100 行代码,而这只是其中之一。难以置信。
            • 在子视图布局时添加插入会剪切单元格内容,如果它是使用自动布局呈现的。
            【解决方案11】:

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

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

            【讨论】:

            • 透明背景不是一个好主意。否则,它可能会起作用。
            • 这是真的。不是所有情况的解决方案,但它适用于某些情况! @ergunkocak
            【解决方案12】:

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

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

            【讨论】:

            • 以这种方式应用layoutMargins 后,我看不到任何视觉变化。也许是因为我正在使用自动布局。
            • 边距不会“破坏”单元格的明确高度,因此您需要为单元格设置自动高度才能使其正常工作
            • 我确实有自动高度。
            【解决方案13】:

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

            【讨论】:

              【解决方案14】:

              使用 UITableViewDelegate,heightForRowAtIndexPath 并返回行高。

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

              【讨论】:

              • 问题是如何在单元格之间添加间距而不是单元格的高度
              【解决方案15】:

              swift 3 中的示例..

              1. 创建单视图应用程序
              2. 在视图控制器中添加表格视图
              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(in tableView: UITableView) -> Int { 返回数组表.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

              【讨论】:

              • 它重复了另一个答案,@Suragch 之前已经回答了 swift 版本,请避免重复
              • 这不是一个好的解决方案。如果您需要带有标题的标题部分,这将不起作用
              【解决方案16】:

              这篇文章有帮助,这几乎是其他答案所说的,但总结和简洁

              https://medium.com/@andersongusmao/left-and-right-margins-on-uitableviewcell-595f0ba5f5e6

              在其中,他仅将它们应用于左侧和右侧,但 UIEdgeInsetsMake init 允许为所有四个点添加填充。

              func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets

              说明
              为按钮或视图创建边缘插图。 插入是矩形周围的边距。正值表示距矩形中心较近的边距,而负值表示距中心较远的边距。

              参数
              顶部:对象顶部的插图。
              left:对象左侧的插图
              底部:对象底部的插图。
              right:对象右侧的插图。

              退货
              按钮或视图的插图

              注意,UIEdgeInsets 也可以用来实现相同的效果。

              Xcode 9.3/Swift 4

              【讨论】:

              • 这个答案错误地表示代码与 Swift 4 兼容,但 UIEdgeInsetsMake 已被弃用。应该使用 UIEdgeInsets。
              • developer.apple.com/documentation/uikit/… 到底在哪里说它已被弃用?我在我的项目中使用它并且我正在使用最新的 Xcode,因此 Swift 9.3 @José
              • 你是对的,对不起,我的错。 UIEdgeInsets 是首选,但这并不意味着另一个已弃用。 SwiftLint 在使用 UIEdgeInsetsMake 时会抱怨遗留构造函数。
              • 好的,知道了。如果您是投了票的人,请删除反对票,我从来没有说过我的答案是唯一可能的。
              • 它说除非你改变你的答案,否则我不能改变我的投票。你能稍微调整一下措辞吗?
              【解决方案17】:

              查看我的solution on GitHub 子类UITableView 并使用Objective-C 的运行时特性。
              它基本上使用Apple的私有数据结构UITableViewRowData,我搜索了UITableView的私有运行时标头:

              https://github.com/JaviSoto/iOS10-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UITableView.h,

              这里是所需的私有类,它包含你需要的所有东西来布局你的单元格的间距,但是你不需要在单元格的类中设置它:

              https://github.com/JaviSoto/iOS10-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UITableViewRowData.h

              【讨论】:

                【解决方案18】:

                基于 Husam 的回答:使用单元格层而不是内容视图允许在整个单元格和附件周围添加边框(如果需要)。这种方法需要仔细调整单元格的底部约束以及那些插图,否则视图将不正确。

                @implementation TableViewCell
                
                - (void)awakeFromNib { 
                    ... 
                }
                
                - (void) layoutSubviews {
                    [super layoutSubviews];
                
                    CGRect newFrame = UIEdgeInsetsInsetRect(self.layer.frame, UIEdgeInsetsMake(4, 0, 4, 0));
                    self.layer.frame = newFrame;
                }
                
                @end
                

                【讨论】:

                  【解决方案19】:

                  我在同一条船上。起初我尝试切换到部分,但在我的情况下,它最终比我最初想象的更令人头疼,所以我一直在寻找替代方案。为了继续使用行(而不是弄乱您访问模型数据的方式),这对我来说只需使用掩码

                  func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
                  {
                      let verticalPadding: CGFloat = 8
                  
                      let maskLayer = CALayer()
                      maskLayer.cornerRadius = 10    //if you want round edges
                      maskLayer.backgroundColor = UIColor.black.cgColor
                      maskLayer.frame = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: cell.bounds.width, height: cell.bounds.height).insetBy(dx: 0, dy: verticalPadding/2)
                      cell.layer.mask = maskLayer
                  }
                  

                  您剩下要做的就是将单元格的高度变大与您想要的verticalPadding 相同的值,然后修改您的内部布局,以便任何与边缘有间距的视图单元格的间距相同,增加了verticalPadding/2。小缺点:你在 tableView 的顶部和底部都有verticalPadding/2 填充,但你可以通过设置tableView.contentInset.bottom = -verticalPadding/2tableView.contentInset.top = -verticalPadding/2 快速解决这个问题。希望这对某人有帮助!

                  【讨论】:

                  • 也适用于 Swift 5。
                  • 最佳答案!!谢谢你。如果使用自定义单元格,那么这适用于“覆盖 func awakeFromNib()”
                  【解决方案20】:

                  我无法让它与单元格中的背景颜色和附件视图一起使用。最终不得不:

                  1) 使用设置了背景颜色的 UIView 设置单元格背景视图属性。

                  let view = UIView()
                  view.backgroundColor = UIColor.white
                  self.backgroundView = view
                  

                  2) 在 layoutSubviews 中重新定位这个视图以添加间距的想法

                  override func layoutSubviews() {
                      super.layoutSubviews()
                      backgroundView?.frame = backgroundView?.frame.inset(by: UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0)) ?? CGRect.zero
                  }
                  

                  【讨论】:

                    【解决方案21】:

                    我在 Swift 4 中以这种方式解决了它。

                    我创建了 UITableViewCell 的扩展并包含以下代码:

                    override open var frame: CGRect {
                        get {
                            return super.frame
                        }
                        set (newFrame) {
                            var frame =  newFrame
                            frame.origin.y += 10
                            frame.origin.x += 10
                            frame.size.height -= 15
                            frame.size.width -= 2 * 10
                            super.frame = frame
                        }
                    }
                    
                    override open func awakeFromNib() {
                        super.awakeFromNib()
                        layer.cornerRadius = 15
                        layer.masksToBounds = false
                    }
                    

                    希望对你有帮助。

                    【讨论】:

                    • 单元格中的文本被裁剪。
                    • CGRect 覆盖正在工作,我没有添加 awakeFromNib 。
                    • 这是一个不错的解决方案。
                    【解决方案22】:

                    如果您不想使用任何标题,我想使用标题作为间距会很好。否则,可能不是最好的主意。我在想的是创建一个自定义单元格视图。

                    例子:

                    在自定义单元格中,创建一个带有约束的背景视图,这样它就不会填满整个单元格,给它一些填充。

                    然后,让tableview背景不可见并去掉分隔符:

                    // Make the background invisible
                    tableView.backgroundView = UIView()
                    tableView.backgroundColor = .clear
                    
                    // Remove the separators
                    tableview.separatorStyle = .none
                    

                    【讨论】:

                      【解决方案23】:

                      如果您不想更改表格视图的部分和行号(就像我所做的那样),请执行以下操作:

                      1) 在表格单元格视图的底部添加一个 ImageView。

                      2) 使其与表格视图的背景颜色相同。

                      我已经在我的应用程序中完成了这项工作,并且效果很好。干杯! :D

                      【讨论】:

                        【解决方案24】:

                        不需要使用一堆不同的部分。其他答案使用帧插图和 CGRect 和图层和...... BLAH。不好;使用自动布局和自定义 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)
                                ])
                            }
                        }
                        

                        【讨论】:

                          【解决方案25】:
                          1. 使用节而不是行
                          2. 每个部分应返回一行
                          3. 使用indexPath.section而不是row分配您的单元格数据
                          4. 实现 UITableView 委托方法heightForHeader 并返回您想要的间距

                          【讨论】:

                            【解决方案26】:

                            您可以像这样在代码中简单地使用约束:

                            class viewCell : UITableViewCell 
                            {
                            
                            @IBOutlet weak var container: UIView!
                            
                            
                            
                            func setShape() {
                                self.container.backgroundColor = .blue
                                self.container.layer.cornerRadius = 20
                                container.translatesAutoresizingMaskIntoConstraints = false
                                self.container.widthAnchor.constraint(equalTo:contentView.widthAnchor , constant: -40).isActive = true
                                       self.container.heightAnchor.constraint(equalTo: contentView.heightAnchor,constant: -20).isActive = true
                                       self.container.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
                                       self.container.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
                            
                                }
                            }
                            

                            添加子视图(容器)并将其他元素放入其中很重要。

                            【讨论】:

                            • 在运行时设置约束效率非常低:)
                            • 什么意思?我在 viewdidappear 中调用 setshape
                            • 尝试对所有视图执行此操作,并尽可能快地滚动您的列表。我想你会看到一个滞后。另外,我真的找不到“这个方法应该在 viewDidAppear() 内部调用”这句话有什么想法吗?
                            【解决方案27】:

                            将 section 中的行数更改为 1 您更改了节数而不是行数

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

                            在此处设置行间距

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

                            【讨论】:

                              【解决方案28】:

                              我重写了这个函数是 UITableViewCell 的子类,它对我来说没问题

                              override func layoutSubviews() {
                                    super.layoutSubviews()
                                    //set the values for top,left,bottom,right margins
                                    let margins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)
                                    contentView.frame = contentView.frame.inset(by: margins)
                                    contentView.layer.cornerRadius = 8
                              }
                              

                              【讨论】:

                                【解决方案29】:

                                这是实际的解决方案

                                使用部分而不是行,因为每一行都有 1 个部分,因此您可以为页眉和页脚留出空间,这里的代码只是将其粘贴到您创建 tableview 出口的 viewcontroller 类中

                                如果你想要顶部间距,只需使用 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
                                    }
                                

                                【讨论】:

                                  【解决方案30】:

                                  阅读其他人的答案后阅读本文

                                  我想警告所有想要使用该解决方案的人,例如添加用于间距目的的标题。如果这样做,您将无法为单元格插入、删除等设置动画。例如,如果您使用该方法可能会出现这种错误

                                  Invalid update: invalid number of sections. The number of sections contained in the table view after the update (6) must be equal to the number of sections contained in the table view before the update (5), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).

                                  如果您需要对行的插入和删除进行动画处理,我会在单元格本身中添加此空间。如果您担心突出显示,那么您可以覆盖方法
                                  func setHighlighted(_ highlighted: Bool, animated: Bool) 并自己设置突出显示

                                  【讨论】:

                                    猜你喜欢
                                    • 2013-09-15
                                    • 2020-04-08
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2014-06-16
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多