ios 如何在 UITableViewCell 之间添加间距

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6216839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:12:02  来源:igfitidea点击:

How to add spacing between UITableViewCell

iosobjective-cuitableview

提问by saili

Is there any way to add spacing between UITableViewCell?

有什么办法可以增加间距UITableViewCell吗?

I have created a table and each cell only contain an image. The image is assigned to the cell like this:

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

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

but this make the image enlarged and fit into the whole cell, and there are no spacing between the images.

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

Or lets say in this way, the height of image are e.g. 50, and I want to add 20 spacing between the images. Is there any way to accomplish this?

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

回答by Suragch

Swift Version

迅捷版

Updated for Swift 3

为 Swift 3 更新

This answer is somewhat more general than the original question for the sake of future viewers. It is a supplemental example to the basic UITableView example for Swift.

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

enter image description here

在此处输入图片说明

Overview

概述

The basic idea is to create a new section (rather than a new row) for each array item. The sections can then be spaced using the section header height.

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

How to do it

怎么做

  • Set up your project as described in UITableView example for Swift. (That is, add a UITableViewand hook up the tableViewoutlet to the View Controller).

  • In the Interface Builder, change the main view background color to light blue and the UITableViewbackground color to clear.

  • Replace the ViewController.swift code with the following.

  • 按照Swift 的 UITableView 示例中所述设置您的项目。(也就是说,添加一个UITableView并将tableView插座连接到视图控制器)。

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

  • 将 ViewController.swift 代码替换为以下内容。

ViewController.swift

视图控制器.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).")
    }
}

Note that indexPath.sectionis used rather than indexPath.rowin order to get the proper values for the array elements and tap positions.

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

How did you get the extra padding/space on the right and left?

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

I got it the same way you add spacing to any view. I used auto layout constraints. Just use the pin toolin the Interface Builder to add spacing for the leading and trailing constraints.

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

回答by Husam

My easy solution using Swift:

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

// Inside UITableViewCell subclass

override func layoutSubviews() {
    super.layoutSubviews()

    contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
}

Resultenter image description here

结果在此处输入图片说明

回答by JonatWang

The way I achieve adding spacing between cells is to make numberOfSections = "Your array count" and make each section contains only one row. And then define headerView and its height.

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

回答by Flea

I needed to do the same concept of having UITableCells have a "space" between them. Since you can't literally add space between cells you can fake it by manipulating the UITableView's cell height and then adding a UIView to the contentView of your cell. Here is a screen shot of a prototype I did in another test project when I was simulating this:

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

Spacing between UITableViewCells

UITableViewCells 之间的间距

Here is some code (Note: there are lots of hard coded values for demonstration purposes)

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

First, I needed to set the heightForRowAtIndexPathto allow for different heights on the UITableViewCell.

首先,我需要设置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;
}

Next, I want to manipulate the look and feel of the UITableViewCells so I do that in the willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPathmethod.

接下来,我想操纵 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];

    }
}

Note that I made my whiteRoundedCornerView height 70.0 and that's what causes the simulated space because the cell's height is actually 80.0 but my contentView is 70.0 which gives it the appearance.

请注意,我将 whiteRoundedCornerView 的高度设为 70.0,这就是导致模拟空间的原因,因为单元格的高度实际上是 80.0,但我的 contentView 是 70.0,这给了它外观。

There might be other ways of accomplishing this even better but it's just how I found how to do it. I hope it can help someone else.

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

回答by Chanok

You will have to set frame to your image. Untested code is

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

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

回答by mehmetkoca

Swift 4.2 Solution

Swift 4.2 解决方案

// Inside UITableViewCell subclass
override func layoutSubviews() {    
    super.layoutSubviews()

    contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
}

回答by Merricat

I was in the same boat. At first I tried switching to sections, but in my case it ended up being more of a headache than I originally thought, so I've been looking for an alternative. To keep using rows(and not mess with how you access your model data), here's what worked for me just by using a mask:

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

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
}

All you have left to do is make the cell's height biggerby the same value as your desired verticalPadding, and then modify your inner layout so that any views that had spacing to the edges of the cell have that same spacing increased by verticalPadding/2. Minor downside: you get verticalPadding/2padding on both the top and bottom of the tableView, but you can quickly fix this by setting tableView.contentInset.bottom = -verticalPadding/2and tableView.contentInset.top = -verticalPadding/2. Hope this helps somebody!

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

回答by Craig

I think the most straight forward solution if your just looking for a little space and probably least expensive would be to simply set the cell border color to your tables background color then set the border width to get desired result!

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

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

回答by Ferruccio

If you are not using section headers (or footers) already, you can use them to add arbitrary spacing to table cells. Instead of having one section with n rows, create a table with n sections with one row each.

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

Implement the tableView:heightForHeaderInSection:method to control the spacing.

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

You may also want to implement tableView:viewForHeaderInSection:to control what the spacing looks like.

您可能还想实现tableView:viewForHeaderInSection:控制间距的外观。

回答by JulianKro

I solved it like this way in Swift 4.

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

I create a extension of UITableViewCell and include this code:

我创建了 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
}

I hope it helps you.

我希望它能帮助你。