50

I want a space between two cell in table view,

I want cell like this,

enter image description here

How can i do that?

Charan
  • 4,940
  • 3
  • 26
  • 43
Ankit Chauhan
  • 2,375
  • 6
  • 25
  • 37
  • You should create custom cell and for that Please refer [Link 1](http://www.e-string.com/content/custom-uitableviewcells-interface-builder) and [Link 2](http://adeem.me/blog/2009/05/30/iphone-sdk-tutorial-part-6-creating-custom-uitableviewcell-using-interface-builder-uitableview/) – Mehul Mistri Aug 25 '11 at 11:26
  • Look at my answer down the bottom. – Gil Sand Jan 27 '15 at 10:11

26 Answers26

124

you can't set distance between cells directly, but you can set the height for header in section to achieve the same result.

1.set the numbers of cell you need as sections:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 3; // in your case, there are 3 cells
}

2.return only 1 cell for each section

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

3.set the height for header in section to set space between cells

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.; // you can have your own choice, of course
}

4.set the header's background color to clear color, so it won't look weird

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}
Brian
  • 30,156
  • 15
  • 86
  • 87
  • 1
    It is good, but distance can be created without using this way also. link "http://stackoverflow.com/questions/11453366/error-creating-custom-tableview-separator/11454239#11454239". – iPhone Programmatically Mar 06 '13 at 07:54
  • An Excellent Approach. – WaaleedKhan Jan 27 '15 at 12:25
  • This answer was very helpful for me. [Here is a Swift version.](http://stackoverflow.com/a/33931591/3681880) – Suragch Nov 26 '15 at 06:21
  • Great but it will add header for first cell too, also it will not allow to pass data from an array in cellForRowAtIndexPath since all the cells will be filled with the first element of the array. –  Apr 22 '16 at 09:10
  • If you don't want to add header to the first cell, just add a if/else statement in `heightForHeaderInSection`. For the array issue, just use `indexPath.section` as the array index(instead of `indexPath.row`). What you mentioned are not problems at all. – Brian Apr 25 '16 at 03:23
  • It's just not correct - it's a dirty way, because Sections and Cells are different concepts and when you use this way, you can't use Sections the way they should be used. This will lead to problems when your database grows, because you will not structure your data representation properly. averydev's answer is correct - use custom spacer cells. – Walter White Jul 12 '17 at 07:42
27

The Best way to get space between two cells in TableView, declare the numbers of sections you want in delegate method of numberofsections this way

For example you have array of 10 objects

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return [array count]; //array count returns 10
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return 1;// this should be one because it will create space between two cells if you want space between 4 cells you can modify it.
}

Then the important point is in cellForRowAtIndexPath delegate method you need to use indexpath.section but not indexpath.row

cell.textLabel.text=[NSString stringWithFormat:@"%@",[array objectAtIndex:indexPath.section]];

That is is check your tableview for the space between two cells. Enjoy!

obaid
  • 892
  • 11
  • 25
23

You can create a Sections of TableView also in the UITableView... This methods are compulsory so create sections and in each section you can create single cell as in your picture..

DShah
  • 9,768
  • 11
  • 71
  • 127
  • But how u will maintain that array which we are giving in the cellforrowindexpath ....i am facing problem that my every cell printing the same element in every section row. Any idea?? – The iCoder May 24 '12 at 08:00
  • @PavanMore: What is your exact scenario?? It is easy to maintain array. Just declare the property of NSArray and initialize it. Then based on cellForRowIndexpath i.e. Index of cell just change the cell text. its easy... if your scenario is different then please elaborate it. – DShah May 25 '12 at 09:41
  • 1
    If you have both multiple sections and rows, try this way http://www.stackoverflow.com/a/29258935/2446178 – JRam13 Mar 25 '15 at 15:50
  • This is easiest way,I found so far,but if you need to use sections and rows and avoid overload of extra ones,try adding elements on UIView,instead directly in content view.Also,add constraints accordingly. – Rajal Jul 17 '15 at 10:19
17

The multiple sections answer would work, but it's extremely brittle, and doesn't allow for actual sections. Instead, you should create a custom cell, or custom cell prototype that simply has a gap at the bottom and/or top.

Use your struts and springs in IB to maintain that uniform gap, and use heightForRowAtIndexPath to return a height that includes the gap.

averydev
  • 5,717
  • 2
  • 35
  • 35
  • It's not brittle - I don't think - but it's kinda hackish. I've made the gap part of the cell in my solution before finding this page but it comes with drawbacks too. In my case it makes the cell design much more complicated than it would be if the gap were managed by the table. YMMV. – n13 Apr 10 '14 at 07:21
  • this makes the editing actions look like crap, the pseudo margin is actually a part of the cell, so in the case you have editing actions, the action view appears to be taller than the view – Tyler Jun 29 '15 at 22:37
  • The default selection and editing modes do look bad, but those are easily overridden... – averydev Jun 14 '16 at 00:10
  • This, like practically every other answer, does not work with dynamically sized cells where the height is calculated by their constraints: Adding a subview won't help unless you then also find all affected constraints and update them accordingly, which gets very complex, quickly. – Thomas Tempelmann Jul 14 '17 at 16:19
  • @ThomasTempelmann I assume you have a good reason to size the cells based on constraints, but I've never found a great reason to do that. The closest i've come is to create a "template cell" based on constraints, populating it manually off screen, and then using the resulting size. – averydev Jul 17 '17 at 19:44
14

Objective - C

 UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 3)];/// change size as you need.       
 separatorLineView.backgroundColor = [UIColor whiteColor];// you can also put image here
 [cell.contentView addSubview:separatorLineView];

Swift 3 (This same will work for Swift 4 also)

var separatorLineView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 3))
/// change size as you need.       
separatorLineView.backgroundColor = UIColor.white
// you can also put image here
cell.contentView.addSubview(separatorLineView)

It worked for me.

Pradumna Patil
  • 2,180
  • 3
  • 17
  • 46
11

If someone looking for Swift version. Here you go.

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 10; // space b/w cells
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return items.count // count of items
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = UIView()
    header.userInteractionEnabled = false
    header.backgroundColor = UIColor.clearColor()
    return header
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
Adnan
  • 5,025
  • 5
  • 25
  • 44
  • 2
    I would recommend doing header.userInteractionEnabled = false so the clear header view does not receive touches. In case the view is overlapping a button. – Alex Lacayo Jul 10 '15 at 05:29
7

For people that looking for alternative way of showing gaps between cells without using sections, you may want to show alternate colours and height like below. Use clearColor for the spacing.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    if (indexPath.row % 2 == 1)
    {
        static NSString *CellIdentifier = @"cellID1";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                            reuseIdentifier:CellIdentifier];
        }

        cell.backgroundColor = [UIColor colorWhite];

        return cell;

    } else {

        static NSString *CellIdentifier2 = @"cellID2";
        UITableViewCell *cell2 = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        if (cell2 == nil) {
            cell2 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                            reuseIdentifier:CellIdentifier2];
        }
        cell2.backgroundColor = [UIColor clearColor];

        return cell2;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 2 == 1) {
        return 40.0;
    } else {
        return 2.0;
    }
}
  • How do you calculate number of row in a single section table – mask Aug 15 '14 at 23:23
  • Based on your content array. Eg: `-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [menus count]; }` – Khairulnizam Dahari Aug 16 '14 at 00:04
  • Its not working. For exmaples arrays count 10 and when I have use this code in cellForRowAtIndexPath and heightForRowAtIndexPath but its return only 5 rows because I think based on this condition if (indexPath.row % 2 == 1). – Nikunj Jadav Apr 16 '15 at 11:41
6

Add these lines in the cellForRowAtIndexPath UITableViewDelegate method before returning the cell.

let separator = UIView(frame: CGRectMake(0, 0, cell!.bounds.size.width, 1))
separator.backgroundColor = UIColor.whiteColor()
cell.contentView.addSubview(separator)
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
PAC
  • 1,664
  • 1
  • 18
  • 24
5

Sometimes, you might really want to keep the tableview divided in rows, and have 1 section. For example, this could happen if you need to display a custom header for that table view that stays in place when you scroll through the section.

What I would recommend doing in this case, is returning a bigger float than the normal height of a cell in:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

and then making sure that the table style is Plain, and that the cell separator is none. You can do that in the XIB file itself, or in code:

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; self.tableView.style = UITableViewStylePlain;

Maybe also add the cell's selection style to none (otherwise it will look like you are selecting more than just the visible part of the cell).

cell.selectionStyle = UITableViewCellSelectionStyleNone;

This will give the impression of space between the cells, but at the same time keeping them as rows in one section (which sometimes is what you want).

Alex
  • 7,432
  • 20
  • 75
  • 118
5

I have used a simple and quick approach for this (using storyboard)

  • Add UITableView in your controller
  • Set the separator style to none (from attributes inspector)
  • Set the height of the row 5 pts more from top and bottom from the desired height
  • Now add an image in the cell, pin it from left and right but leave 5 pts space (for padding like feel) and set the background of the image same as the background you want for cell

When the table view will be loaded, it will feel like there are spaces between cells.

Abdullah Saeed
  • 3,065
  • 1
  • 15
  • 27
4

For spacing between cells like the ones in your screenshot, there is no need for custom cells (for their look anyway, like the gradient bkg and so on, this could anyway be a good idea, but this won't help for your spacing between cells)

To achieve this kind of spacing, simply use different sections in your UITableView.

[EDIT] Everything is explained In Apple's TableView Programming Guide (and that's worth reading it, as it contains a lot of stuff you should know about tableviews)

AliSoftware
  • 32,623
  • 6
  • 82
  • 77
3

The best way to do that using xib file. give top and bottom constraint to it. for example, here I give bottom constraint 10 and make sure give perfect height to cell as shown as given below.here in code 'joinTableViewCell' is fileName of xib file.

enter image description here

extension JoinTableViewController: UITableViewDataSource,UITableViewDelegate {
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = Bundle.main.loadNibNamed("joinTableViewCell", owner: self, options: nil)?.first as! joinTableViewCell
        cell.ImgView.layer.masksToBounds = true
        cell.ImgView.cornerRadius(cell.ImgView.bounds.width / 2)
        cell.lblName.text = "Christian Bell"
        cell.lblJoin.text = "Joined"+"\t"+"Sep 3"
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    
    
    
}
2

What you're trying to achieve, visually, would be the same as adding the content of each cell inside a container View with a gray background, and having that view inside the cell. I don't think there's a need to add spaces between cells.

jacklehamster
  • 311
  • 3
  • 6
2

I don't know why all the answers that complicated. KIS, only using storyboard I've put a UIView inside the tableCell Content View; now the UIView height is less than Content View height, and that's it!

Play with the Content View color and the UIView color to get the desired result.

Yizhar
  • 875
  • 9
  • 11
2

My easy solution using Swift :

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

or one line code

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

Result enter image description here

Husam
  • 8,149
  • 3
  • 38
  • 45
  • You should give a higher height in `heightForRowAtIndexPath` then add inset @UtkuDalmaz – Husam Apr 24 '16 at 12:24
2

* WORKING WITH IOS 9 XCODE 7.3 *

The most straight forward way to achieve this is to simply add this code to your cellForRowAtIndexPath method.

    cell.separatorInset.left = 20.0
    cell.separatorInset.right = 20.0
    cell.separatorInset.top = 20.0
    cell.separatorInset.bottom = 20.0
    cell.layer.borderWidth = 3
    cell.layer.cornerRadius = 20.0
    cell.layer.borderColor = UIColor.flatSkyBlueColorDark().CGColor

Then go to your story board and click on the tableview. Go to identity inspector and change the View's background color to whatever border color was set in the method. Voila! Play with the values to get the desired output. Hope this helps!

Note: If using Chameleon library you must set the background color for the view in code, not via the story board plugin. For some reason the color seems to be off by a shade.

Craig
  • 553
  • 7
  • 13
1

Well what I did is simply simulate the space by creating a simple custom cell that is a little larger than what I want (cell + gap/2), and then put all my cell's content in an inner-view.

Then put your cell's topmost view as the color of your background, and the inner-view as your actual cell. And you'll have the illusion of having space between cells, when it's actually just a larger cell with borders.

Gil Sand
  • 5,802
  • 5
  • 36
  • 78
0

You don't have to assign each section for each cell. Just create a UIView (container) inside your cell, margin it with cell's view. And we layout components like label, text, image on that container.

Gintama
  • 1,152
  • 20
  • 35
0

I suggest to create a custom UITableViewCell base class and use this class like below,

  1. Create custom UITableViewCell class
  2. Create a UIView in new class, this will act as the 'baseContentView' and it will be immediate child of 'UITableViewCell.contentView'
  3. Adjust the top 'padding' on 'baseContentView' (this will be the separator/gap) from parent view (UITableViewCell.contentView)
  4. Inherit all your custom classes from this class rather than UITableViewCell
  5. Add all the content/subviews to 'baseContentView' rather than 'self.contentView'

You can play with the 'padding' as per your need.

Hiren Dhamecha
  • 658
  • 5
  • 15
infiniteLoop
  • 2,135
  • 1
  • 25
  • 29
0
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return __titlesArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc]init];
    header.backgroundColor = [UIColor clearColor];
    return header;

}
Ahmed Abdallah
  • 2,338
  • 1
  • 19
  • 30
0

I use like:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 194.0;
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.contentView.backgroundColor = UIColor.clearColor()
    let whiteRoundedView : UIView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 185))

    whiteRoundedView.backgroundColor = UIColor( red: CGFloat(61.0/255.0), green: CGFloat(117.0/255.0), blue: CGFloat(147.0/255.0), alpha: CGFloat(1.0))

    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 3.0
    whiteRoundedView.layer.shadowOffset = CGSizeMake(-1, 1)
    whiteRoundedView.layer.shadowOpacity = 0.5
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubviewToBack(whiteRoundedView)
}

Get Color Code RGB values from:

enter image description here

Mannam Brahmam
  • 2,225
  • 2
  • 24
  • 36
0

1) first create 2 sections in table view. 2) create an empty cell. 3) create the cell with data you want to display. 4) use the method

  • (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section==0) {

    if (indexPath.row % 2 != 1) { return 15.0; } else { return 100; } } else

    if (indexPath.row % 2 != 1) {
        return 100.0;
    } else {
        return 15.0;
    }
    

}

It will add space between the cells. It worked for me.

0

Here is my method with Swift 3:

In ViewDidLoad(), add:

self.tableView.rowHeight = 500.0

In tableview "CellForRowAt", add following:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    // Configure the cell...
    var actualContentView = UIView()
    actualContentView.frame = CGRect(x: 10, y: 10, width: cell.contentView.frame.width - 20, height: cell.contentView.frame.height - 20)
    actualContentView.backgroundColor = UIColor.blue
    cell.contentView.addSubview(actualContentView)

    return cell
}
R Dragon
  • 981
  • 8
  • 9
0

in your cellForRowAt

cell.layer.borderWidth = 2
cell.layer.cornerRadius = 10
cell.layer.borderColor = UIColor.systemBackground.cgColor
Timchang Wuyep
  • 629
  • 7
  • 10
0

In Table View DataSource there are two methods named number of sections and number of rows In sections return 3; In Rows return 1;

kiran kumar
  • 27
  • 10
-1

I have checked all the answers but I think this is the easiest way:

 UIView * theContentView = [UIView alloc]initWithFrame:CGRectMake(0,gap,width,height)];
 theContentView.backgroundcolor = [UIColor lightGrayColor];//contentColor
 cell.backgroundcolor = [UIColor blackColor];//gapColor
 [cell addSubview: theContentView]

The prototype code says You can create a subview to show the content of cell and the rest is the gap as you wish.

PeiweiChen
  • 413
  • 5
  • 16