Ios 如何在UITableViewCell之间添加间距

Ios 如何在UITableViewCell之间添加间距,ios,objective-c,uitableview,Ios,Objective C,Uitableview,有没有办法在UITableViewCell之间添加间距 我创建了一个表,每个单元格只包含一个图像。将图像指定给单元格,如下所示: cell.imageView.image = [myImages objectAtIndex:indexPath.row]; 但这会使图像放大并适合整个细胞,并且图像之间没有间隔 或者这样说,图像的高度是50,我想在图像之间增加20个间距。有什么方法可以做到这一点吗?您必须为图像设置帧。未经测试的代码是 cell.imageView.frame = CGRectOf

有没有办法在
UITableViewCell
之间添加间距

我创建了一个表,每个单元格只包含一个图像。将图像指定给单元格,如下所示:

cell.imageView.image = [myImages objectAtIndex:indexPath.row];
但这会使图像放大并适合整个细胞,并且图像之间没有间隔


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

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

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

我可以想到三种方法:

  • 创建一个自定义表格单元格,该单元格将按照所需的方式布局整个单元格的视图

  • 而不是将图像添加到 图像视图,清除的子视图 在“图像”视图中,创建自定义 视图,该视图为图像和另一个视图(可能是提供所需间距的简单UIView)添加UIImageView,并将其添加为图像的子视图 图像视图

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

  • 这有意义吗?

    如果您尚未使用节头(或页脚),则可以使用它们向表格单元格添加任意间距。创建一个包含n个部分的表,而不是一个部分包含n行,每个部分包含一行

    执行
    tableView:heightForHeaderInSection:
    方法来控制间距


    您可能还需要实现
    tableView:viewForHeaderInSection:
    ,以控制间距的大小。

    我需要执行相同的概念,即让UITableCell在它们之间有一个“空间”。由于无法在单元格之间添加空间,因此可以通过操纵UITableView的单元格高度,然后将UIView添加到单元格的contentView来伪造它。这是我在另一个测试项目中模拟的一个原型的屏幕截图:

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

    首先,我需要为rowatinexpath设置
    高度,以允许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的外观,以便在rowatindexpath:(nsindepath*)indepath
    方法的
    willDisplayCell:(NewsUITableViewCell*)单元格中进行操作

    - (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,这赋予了它外观


    也许还有其他更好的方法来实现这一点,但这只是我发现如何做到这一点的方式。我希望它能帮助其他人。

    我实现增加单元格间距的方法是使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;
    }
    

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

    尝试查看内部视图 -(UIEdgeInsets)布局边距; 在单元格上

    Swift版本 更新为Swift 3

    为了未来的观众,这个答案比原来的问题更一般。这是对基本原理的补充示例

    概述

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

    如何做

    • 按照中所述设置项目。(即,添加
      UITableView
      并将
      tableView
      出口连接到视图控制器)

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

    • 用以下代码替换ViewController.swift代码

    ViewController.swift

    请注意,为了获得数组元素和点击位置的正确值,使用了
    indexPath.section
    ,而不是
    indexPath.row

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


    我得到它的方法和你给任何视图添加间距的方法一样。我使用了自动布局约束。只需在界面生成器中使用添加前导约束和尾随约束的间距。

    我的情况是我使用自定义UIView查看截面中的ForHeader,也使用heightForHeader返回恒定高度,例如40,问题是当没有数据时,所有的页眉视图都相互接触。所以我想在没有数据的情况下在部分之间留出空间,所以我通过将“tableview样式”平面更改为“Group”来进行修复。这对我来说很有效

    使用Swift的简易解决方案:

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

    我认为,如果您只是想找一点空间,而且可能成本最低,那么最直接的解决方案就是将单元格边框颜色设置为表格背景颜色,然后设置边框宽度以获得所需的结果

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

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

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

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

    swift 3中的示例

  • 折皱单个视图应用程序
  • 在视图控制器中添加tableview
  • 为tablview单元格添加自定义单元格
  • 视图控制器代码如下所示

       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{ 返回arraytable.count }

  • 将完整源代码下载到Github:link


  • 这篇文章很有帮助,它和其他答案所说的差不多,但它是总结和简洁的

    在其中,他只将它们应用于左侧和右侧,但
    UIEdgeInsetsMake
    init允许添加填充
       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 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
      }
    
       }
    
    @implementation TableViewCell
    
    - (void)awakeFromNib { 
        ... 
    }
    
    - (void) layoutSubviews {
        [super layoutSubviews];
    
        CGRect newFrame = UIEdgeInsetsInsetRect(self.layer.frame, UIEdgeInsetsMake(4, 0, 4, 0));
        self.layer.frame = newFrame;
    }
    
    @end
    
    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
    }
    
    let view = UIView()
    view.backgroundColor = UIColor.white
    self.backgroundView = view
    
    override func layoutSubviews() {
        super.layoutSubviews()
        backgroundView?.frame = backgroundView?.frame.inset(by: UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0)) ?? CGRect.zero
    }
    
    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
    }
    
    // Make the background invisible
    tableView.backgroundView = UIView()
    tableView.backgroundColor = .clear
    
    // Remove the separators
    tableview.separatorStyle = .none
    
    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 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
    
        }
    }
    
    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
    }
    
    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
        }
    
    import UIKit
    
    class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
            
            @IBOutlet weak var yourTableView: UITableView!
            
            let yourArray = ["data1", "data2", "data3" /* so on */ ]
    
            let emptyTransparentRowHeight: CGFloat = 10
            
            override func viewDidLoad() {
                super.viewDidLoad()
        
                yourTableView.dataSource = self
                yourTableView.delegate = self
            }
                
    
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return (yourArray.count * 2)
            }
            
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                
                guard indexPath.row % 2 == 0,
                    let usableCell = tableView.dequeueReusableCell(withIdentifier: "Your First Cell Prototype Identifier") as? YourTableViewCellSubClass
                else {
                    
                    return tableView.dequeueReusableCell(withIdentifier: "The Second and Empty Cell Prototype Identifier")!
                }
          
                usableCell.Label?.text = yourArray[indexPath.row/2]
                
                return usableCell
        
            }
            
            func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
                if indexPath.row % 2 == 0 {
                    return tableView.rowHeight
                }
                
                return self.emptyTransparentRowHeight
            }
            
        }