Hide separator line on one UITableViewCell
Asked Answered
I

39

282

I'm customizing a UITableView. I want to hide the line separating on the last cell ... can i do this?

I know I can do tableView.separatorStyle = UITableViewCellStyle.None but that would affect all the cells of the tableView. I want it to only affect my last cell.

Incondite answered 19/12, 2011 at 13:5 Comment(3)
Possible duplicate of Is there a way to remove the separator line from a UITableView?Backflow
Your question answered mine. tableView.separatorStyle = UITableViewCellStyle.None was the line I neededKickshaw
tableView.separatorStyle = .noneGreenhouse
D
398

in viewDidLoad, add this line:

self.tableView.separatorColor = [UIColor clearColor];

and in cellForRowAtIndexPath:

for iOS lower versions

if(indexPath.row != self.newCarArray.count-1){
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 44, 320, 2)];
    line.backgroundColor = [UIColor redColor];
    [cell addSubview:line];
}

for iOS 7 upper versions (including iOS 8)

if (indexPath.row == self.newCarArray.count-1) {
    cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.f);
}
Dayton answered 19/12, 2011 at 13:10 Comment(9)
if this is not working then first set the seperator line color of tableview is self.tableView.separatorColor = [UIColor clearColor]; and add imageview with height of 2 and width whatever you want with color and add into table cell also check the condition of above if match then don't add it in cell.Dayton
This will work on iOS7 and iOS8. It effectively squeezes the separator down to zero. cell.separatorInset = UIEdgeInsetsMake(0, CGRectGetWidth(cell.bounds)/2.0, 0, CGRectGetWidth(cell.bounds)/2.0)Marienthal
One reminder: When your iDevice is iPad and cell is used AutoLayout, the value returned by "cell.bounds.size.width" maybe not equal to actual cell's width. So I always use "tableView.frame.size.width" instead of "cell.bounds.size.width".Admixture
Please note: you should use [cell.contentView addSubview:line] instead of [cell addSubview:line]Claudclauddetta
To get the OP's request to only remove the last separator, disregard this line: self.tableView.separatorColor = [UIColor clearColor];Inartistic
change cell.separatorInset left inset will also change the cell content's left inset. Not just the separator line. From apple doc: "You can use this property to add space between the current cell’s contents and the left and right edges of the table. Positive inset values move the cell content and cell separator inward and away from the table edges."Holpen
For my test, the case of the comment above only apply to cell.textLabel, not apply to custom added view.Holpen
Bad idea. You should never add subviews to a cell in cellForRowAtIndexPath. Remember that cells are reused. Each time this cell is reused you'll add another separator line view. On large lists this may affect scroll performance. And it's just not the right way to do it.Glandulous
The separatorInset trick also pushes any textLabel off-screen.Sadie
L
276

In the UITableViewDataSource cellForRowAtIndexPath method

Swift :

if indexPath.row == {your row number} {
    cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
}

or :

cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, UIScreen.main.bounds.width)

for default Margin:

cell.separatorInset = UIEdgeInsetsMake(0, tCell.layoutMargins.left, 0, 0)

to show separator end-to-end

cell.separatorInset = .zero

Objective-C:

if (indexPath.row == {your row number}) {
    cell.separatorInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, CGFLOAT_MAX);
}
Lauter answered 17/10, 2013 at 6:27 Comment(10)
Doesn't work for a grouped UITableView, while the accepted answer does.Cretaceous
This doesn't work for iOS9, self.tableView.separatorColor = [UIColor clearColor]; fixed it.Bonheur
It's a complete hack but what works in iOS 9 is: cell.layoutMargins = UIEdgeInsetsZero; cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 9999)Bimonthly
This is the way it works for me in iOS 8+: cell.separatorInset = UIEdgeInsetsMake(0.f, 0.f, 0.f, cell.bounds.size.width-cell.layoutMargins.left); If I don't subtract the cell.layoutMargins.left value, the separator line is drawn from the left border to the left margin (if you have any).Vitovitoria
The width should go to the 2nd parameter, check the UIEdgeInsetsMakeMaccarone
I replaced cell.bounds.size.width with CGFLOAT_MAX because the original answer wasn't working on iPad (some part of the separator was still visible). I also added Swift version. This answer tested to work on iOS 9.3 and 10.3 on different devices.Confectioner
This pushes any textLabel off-screen.Sadie
.greatestFiniteMagnitude causes blinking app during back to app on VC with this solution. In my case cell.separatorInset.left = cell.bounds.width works great on iOS 10 & 11.Auguste
it shifts text (title), so useless!Greatgrandaunt
I assume the "else" should be define to reset the inset or is automatically done when reused?Gilpin
P
114

To follow up on Hiren's answer.

in ViewDidLoad and the following line :

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

Or, if you are using XIB's or Storyboards change "separator" to "none" :

Interface builder

And in CellForRowAtIndexPath add this :

CGFloat separatorInset; // Separator x position 
CGFloat separatorHeight; 
CGFloat separatorWidth; 
CGFloat separatorY; 
UIImageView *separator;
UIColor *separatorBGColor;

separatorY      = cell.frame.size.height;
separatorHeight = (1.0 / [UIScreen mainScreen].scale);  // This assures you to have a 1px line height whatever the screen resolution
separatorWidth  = cell.frame.size.width;
separatorInset  = 15.0f;
separatorBGColor  = [UIColor colorWithRed: 204.0/255.0 green: 204.0/255.0 blue: 204.0/255.0 alpha:1.0];

separator = [[UIImageView alloc] initWithFrame:CGRectMake(separatorInset, separatorY, separatorWidth,separatorHeight)];
separator.backgroundColor = separatorBGColor;
[cell addSubView: separator];

Here is an example of the result where I display a tableview with dynamic Cells (but only have a single one with contents). The result being that only that one has a separator and not all the "dummy" ones tableview automatically adds to fill the screen.

enter image description here

EDIT: For those who don't always read the comments, there actually is a better way to do it with a few lines of code :

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()
}
Prescriptible answered 29/10, 2014 at 9:48 Comment(1)
I think, to hide the separator line, this is the right approach. self.tableView.separatorStyle = .noneTodd
H
55

If you don't want to draw the separator yourself, use this:

  // Hide the cell separator by moving it to the far right
  cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);

This API is only available starting from iOS 7 though.

Hyson answered 17/9, 2013 at 13:0 Comment(6)
separatorInset seems to inset the cell content as well as the separator, requiring another hack to compensate: cell.IndentationWidth = -10000;Romans
A better method is to set separatorInset to 0 for top, left and bottom and the cell width for right: cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width); This avoids needing to adjust any other cell properties.Leifleifer
If you're using the cell bounds width for the inset you might need to recalculate when the interface rotates.Hoary
Note that if the cell you do this to gets reused to draw another cell for which you did not intend to hide the separator, the separator will be gone from it also.Foresight
UIEdgeInsetsMake(0, 10000, 0, 0); worked -> UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width); did not. guess that's cause I have a nasty habit of keeping 3.5" sized vcs in xibs and styoryboards which artifacts on 4"+ devices cause 375-320px section = 55px remains. (in yoda voice) and very ugly it is!Dorcas
@Romans indentationWidth hack did not worked for me (ios 13)Incommutable
M
32

Set separatorInset.right = .greatestFiniteMagnitude on your cell.

Male answered 22/8, 2018 at 6:58 Comment(3)
calling this on awakeFromNib can cause the entire screen to flash on applicationDidBecomeActiveBrobdingnagian
This works iOS 12.2, on-device, from programmatic UITableViewCell creation. Nice.Bernetta
Setting right separator worked for me when I'm setting it in cellForRowAt. The best solutions. It works from iOS 10 to 13 for me. Tested on iOS 10, 12 and 13. When left margin is set then it is not working for iOS 10.Vesical
L
30

my develop environment is

  • Xcode 7.0
  • 7A220 Swift 2.0
  • iOS 9.0

above answers not fully work for me

after try, my finally working solution is:

let indent_large_enought_to_hidden:CGFloat = 10000
cell.separatorInset = UIEdgeInsetsMake(0, indent_large_enought_to_hidden, 0, 0) // indent large engough for separator(including cell' content) to hidden separator
cell.indentationWidth = indent_large_enought_to_hidden * -1 // adjust the cell's content to show normally
cell.indentationLevel = 1 // must add this, otherwise default is 0, now actual indentation = indentationWidth * indentationLevel = 10000 * 1 = -10000

and the effect is: enter image description here

Luminiferous answered 28/9, 2015 at 8:46 Comment(0)
A
23

In Swift 3, Swift 4 and Swift 5, you can write an extension to UITableViewCell like this:

extension UITableViewCell {
  func separator(hide: Bool) {
    separatorInset.left = hide ? bounds.size.width : 0
  }
}

Then you can use this as below (when cell is your cell instance):

cell.separator(hide: false) // Shows separator 
cell.separator(hide: true) // Hides separator

It is really better assigning the width of table view cell as left inset instead of assigning it some random number. Because in some screen dimensions, maybe not now but in future your separators can still be visible because that random number may not be enough. Also, in iPad in landscape mode you can't guarantee that your separators will always be invisible.

Airfoil answered 18/6, 2017 at 11:58 Comment(1)
This doesn't works for grouped-style UITableView. Do you have solution for grouped case?Phonetic
C
9

In your UITableViewCell subclass, override layoutSubviews and hide the _UITableViewCellSeparatorView. Works under iOS 10.

override func layoutSubviews() {
    super.layoutSubviews()

    subviews.forEach { (view) in
        if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
            view.hidden = true
        }
    }
}
Crossgarnet answered 11/9, 2016 at 4:44 Comment(2)
none of the above solution worked,, this works on ios 12Ruhnke
This might get rejected from the App Store for accessing private APIs.Typewriter
I
8

Better solution for iOS 7 & 8

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    DLog(@"");
    if (cell && indexPath.row == 0 && indexPath.section == 0) {

        DLog(@"cell.bounds.size.width %f", cell.bounds.size.width);
        cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.0f);
    }
}

If your app is rotatable — use 3000.0f for left inset constant or calc it on the fly. If you try to set right inset you have visible part of separator on the left side of cell on iOS 8.

Insolent answered 30/11, 2014 at 16:49 Comment(1)
Why use a random number when you could do something like this: MAX([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height); to make sure its always goneFeeler
C
7

In iOS 7, the UITableView grouped style cell separator looks a bit different. It looks a bit like this:

enter image description here

I tried Kemenaran's answer of doing this:

cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);

However that doesn't seem to work for me. I'm not sure why. So I decided to use Hiren's answer, but using UIView instead of UIImageView, and draws the line in the iOS 7 style:

UIColor iOS7LineColor = [UIColor colorWithRed:0.82f green:0.82f blue:0.82f alpha:1.0f];

//First cell in a section
if (indexPath.row == 0) {

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];

} else if (indexPath.row == [self.tableViewCellSubtitles count] - 1) {

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];

    UIView *lineBottom = [[UIView alloc] initWithFrame:CGRectMake(0, 43, self.view.frame.size.width, 1)];
    lineBottom.backgroundColor = iOS7LineColor;
    [cell addSubview:lineBottom];
    [cell bringSubviewToFront:lineBottom];

} else {

    //Last cell in the table view
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];
}

If you use this, make sure you plug in the correct table view height in the second if statement. I hope this is useful for someone.

Chagall answered 14/11, 2013 at 23:50 Comment(0)
S
6

In willdisplaycell:

cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
Shiest answered 7/6, 2016 at 23:24 Comment(0)
C
6

The much more simple and logical is to do this:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] initWithFrame:CGRectZero];
}

In most cases you don't want to see only the last table view cell separator. And this approach removes only the last table view cell separator, and you don't need to think about Auto Layout issues (i.e. rotating device) or hardcode values to set up separator insets.

Coroner answered 17/8, 2018 at 13:15 Comment(2)
Welcome to Stack Overflow! A better answer for future readers would explain why this is simpler and more logical.Almeida
a nice solution!Copperplate
A
5

In Swift using iOS 8.4:

/*
    Tells the delegate that the table view is about to draw a cell for a particular row. (optional)
*/
override func tableView(tableView: UITableView,
                        willDisplayCell cell: UITableViewCell,
                        forRowAtIndexPath indexPath: NSIndexPath)
{
    if indexPath.row == 3 {
        // Hiding separator line for only one specific UITableViewCell
        cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
    }
}

Note: this snippet above will work on UITableView using dynamic cells. The only problem that you can encounter is when you use static cells with categories, a separator type different than none and a grouped style for the table view. In fact, in this particular case it will not hide the last cell of each category. For overcoming that, the solution that I found was to set the cell separator (through IB) to none and then creating and adding manually (through code) your line view to each cell. For an example, please check the snippet below:

/*
Tells the delegate that the table view is about to draw a cell for a particular row. (optional)
*/
override func tableView(tableView: UITableView,
    willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath)
{
    // Row 2 at Section 2
    if indexPath.row == 1 && indexPath.section == 1 {
        // Hiding separator line for one specific UITableViewCell
        cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)

        // Here we add a line at the bottom of the cell (e.g. here at the second row of the second section).
        let additionalSeparatorThickness = CGFloat(1)
        let additionalSeparator = UIView(frame: CGRectMake(0,
            cell.frame.size.height - additionalSeparatorThickness,
            cell.frame.size.width,
            additionalSeparatorThickness))
        additionalSeparator.backgroundColor = UIColor.redColor()
        cell.addSubview(additionalSeparator)
    }
}
Allanite answered 29/6, 2015 at 12:29 Comment(3)
In my project, this works for static cells but not for dynamic ones. In the latter case, the content of the last cell is shifted to the right (just like the separator line). Any ideas, why this might happen?Faker
The first snippet of the answer above will work on UITableView using dynamic cells. The only problem that you can encounter is when you use static cells with categories, a separator type different than none and a grouped style for the table view. In fact, in this particular case it will not hide the last cell of each category. For overcoming that, the solution that I found was to set the cell separator (through IB) to none and then creating and adding manually (through code) your line view to each cell. For an example, please check the second snippet of the answer above.Allanite
it shifts text (title), so useless!Greatgrandaunt
H
5

I do not believe this approach will work under any circumstance with dynamic cells...

if (indexPath.row == self.newCarArray.count-1) {
  cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.f);
}

It doesn't matter which tableview method you do it in for dynamic cells the cell you changed the inset property on will always have the inset property set now every time it is dequeued causing a rampage of missing line separators... That is until you change it yourself.

Something like this worked for me:

if indexPath.row == franchises.count - 1 {
  cell.separatorInset = UIEdgeInsetsMake(0, cell.contentView.bounds.width, 0, 0)
} else {
  cell.separatorInset = UIEdgeInsetsMake(0, 0, cell.contentView.bounds.width, 0)
}

That way you update ur data structure state at every load

Hobbema answered 16/9, 2015 at 21:33 Comment(0)
I
4

Use this subclass, set separatorInset does not work for iOS 9.2.1, content would be squeezed.

@interface NSPZeroMarginCell : UITableViewCell

@property (nonatomic, assign) BOOL separatorHidden;

@end

@implementation NSPZeroMarginCell

- (void) layoutSubviews {
    [super layoutSubviews];

    for (UIView *view in  self.subviews) {
        if (![view isKindOfClass:[UIControl class]]) {
            if (CGRectGetHeight(view.frame) < 3) {
                view.hidden = self.separatorHidden;
            }
        }
    }
}

@end

https://gist.github.com/liruqi/9a5add4669e8d9cd3ee9

Irreducible answered 1/2, 2016 at 11:6 Comment(0)
J
3

Using Swift 3 and adopting the fastest hacking-method, you can improve code using extensions:

extension UITableViewCell {

    var isSeparatorHidden: Bool {
        get {
            return self.separatorInset.right != 0
        }
        set {
            if newValue {
                self.separatorInset = UIEdgeInsetsMake(0, self.bounds.size.width, 0, 0)
            } else {
                self.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
            }
        }
    }

}

Then, when you configure cell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
    switch indexPath.row {
       case 3:
          cell.isSeparatorHidden = true
       default:
          cell.isSeparatorHidden = false
    }
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    if cell.isSeparatorHidden { 
       // do stuff
    }
}
Jeromyjerreed answered 28/6, 2017 at 15:5 Comment(0)
Z
2
  if([_data count] == 0 ){
       [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//  [self tableView].=YES;
    } else {
      [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];////    [self tableView].hidden=NO;
    }
Zoller answered 1/12, 2014 at 8:16 Comment(0)
E
2

The best way to achieve this is to turn off default line separators, subclass UITableViewCell and add a custom line separator as a subview of the contentView - see below a custom cell that is used to present an object of type SNStock that has two string properties, ticker and name:

import UIKit

private let kSNStockCellCellHeight: CGFloat = 65.0
private let kSNStockCellCellLineSeparatorHorizontalPaddingRatio: CGFloat = 0.03
private let kSNStockCellCellLineSeparatorBackgroundColorAlpha: CGFloat = 0.3
private let kSNStockCellCellLineSeparatorHeight: CGFloat = 1

class SNStockCell: UITableViewCell {

  private let primaryTextColor: UIColor
  private let secondaryTextColor: UIColor

  private let customLineSeparatorView: UIView

  var showsCustomLineSeparator: Bool {
    get {
      return !customLineSeparatorView.hidden
    }
    set(showsCustomLineSeparator) {
      customLineSeparatorView.hidden = !showsCustomLineSeparator
    }
  }

  var customLineSeparatorColor: UIColor? {
   get {
     return customLineSeparatorView.backgroundColor
   }
   set(customLineSeparatorColor) {
     customLineSeparatorView.backgroundColor = customLineSeparatorColor?.colorWithAlphaComponent(kSNStockCellCellLineSeparatorBackgroundColorAlpha)
    }
  }

  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  init(reuseIdentifier: String, primaryTextColor: UIColor, secondaryTextColor: UIColor) {
    self.primaryTextColor = primaryTextColor
    self.secondaryTextColor = secondaryTextColor
    self.customLineSeparatorView = UIView(frame:CGRectZero)
    super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier:reuseIdentifier)
    selectionStyle = UITableViewCellSelectionStyle.None
    backgroundColor = UIColor.clearColor()

    contentView.addSubview(customLineSeparatorView)
    customLineSeparatorView.hidden = true
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    self.showsCustomLineSeparator = false
  }

  // MARK: Layout

  override func layoutSubviews() {
    super.layoutSubviews()
    layoutCustomLineSeparator()
  }

  private func layoutCustomLineSeparator() {
    let horizontalPadding: CGFloat = bounds.width * kSNStockCellCellLineSeparatorHorizontalPaddingRatio
    let lineSeparatorWidth: CGFloat = bounds.width - horizontalPadding * 2;
    customLineSeparatorView.frame = CGRectMake(horizontalPadding,
      kSNStockCellCellHeight - kSNStockCellCellLineSeparatorHeight,
      lineSeparatorWidth,
      kSNStockCellCellLineSeparatorHeight)
  }

  // MARK: Public Class API

  class func cellHeight() -> CGFloat {
    return kSNStockCellCellHeight
  }

  // MARK: Public API

  func configureWithStock(stock: SNStock) {
    textLabel!.text = stock.ticker as String
    textLabel!.textColor = primaryTextColor
    detailTextLabel!.text = stock.name as String
    detailTextLabel!.textColor = secondaryTextColor
    setNeedsLayout()
  } 
}

To disable the default line separator use, tableView.separatorStyle = UITableViewCellSeparatorStyle.None;. The consumer side is relatively simple, see example below:

private func stockCell(tableView: UITableView, indexPath:NSIndexPath) -> UITableViewCell {
  var cell : SNStockCell? = tableView.dequeueReusableCellWithIdentifier(stockCellReuseIdentifier) as? SNStockCell
  if (cell == nil) {
    cell = SNStockCell(reuseIdentifier:stockCellReuseIdentifier, primaryTextColor:primaryTextColor, secondaryTextColor:secondaryTextColor)
  }
  cell!.configureWithStock(stockAtIndexPath(indexPath))
  cell!.showsCustomLineSeparator = true
  cell!.customLineSeparatorColor = tintColor
  return cell!
}
Emission answered 26/4, 2015 at 7:24 Comment(0)
S
2

For Swift 2:

add the following line to viewDidLoad():

tableView.separatorColor = UIColor.clearColor()
Strobe answered 25/7, 2015 at 12:2 Comment(0)
R
2
cell.separatorInset = UIEdgeInsetsMake(0.0, cell.bounds.size.width, 0.0, -cell.bounds.size.width)

works well in iOS 10.2

enter image description here

Roop answered 11/2, 2017 at 16:38 Comment(0)
C
2

Swift 5 - iOS13+

When you are defininig your table, just add:

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    // Removes separator lines
    tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
    return UIView()
}

The magic line is tableView.separatorStyle = UITableViewCell.SeparatorStyle.none

Cyrille answered 28/7, 2022 at 15:40 Comment(0)
N
1

Try the below code, might help you resolve your problem

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   NSString* reuseIdentifier = @"Contact Cell";

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
if (indexPath.row != 10) {//Specify the cell number
        cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgWithLine.png"]];

} else {
        cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgWithOutLine.png"]];

}

    }

    return cell;
}
Nardone answered 19/12, 2011 at 13:52 Comment(0)
H
1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

       NSString *cellId = @"cell";
       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
       NSInteger lastRowIndexInSection = [tableView numberOfRowsInSection:indexPath.section] - 1;

       if (row == lastRowIndexInSection) {
              CGFloat halfWidthOfCell = cell.frame.size.width / 2;
              cell.separatorInset = UIEdgeInsetsMake(0, halfWidthOfCell, 0, halfWidthOfCell);
       }
}
Hourigan answered 13/12, 2014 at 11:33 Comment(0)
P
1

You have to take custom cell and add Label and set constraint such as label should cover entire cell area. and write the below line in constructor.

- (void)awakeFromNib {
    // Initialization code
    self.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);
    //self.layoutMargins = UIEdgeInsetsZero;
    [self setBackgroundColor:[UIColor clearColor]];
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
}

Also set UITableView Layout margin as follow

tblSignup.layoutMargins = UIEdgeInsetsZero;
Poundage answered 5/3, 2015 at 7:31 Comment(0)
H
1

if the accepted answer doesn't work, you can try this:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f; }

It's great ;)

Hectocotylus answered 10/4, 2015 at 7:30 Comment(0)
F
1

I couldn't hide the separator on a specific cell except using the following workaround

- (void)layoutSubviews {
    [super layoutSubviews];
    [self hideCellSeparator];
}
// workaround
- (void)hideCellSeparator {
    for (UIView *view in  self.subviews) {
        if (![view isKindOfClass:[UIControl class]]) {
            [view removeFromSuperview];
        }
    }
}
Flabbergast answered 14/6, 2015 at 11:3 Comment(0)
R
1

For iOS7 and above, the cleaner way is to use INFINITY instead of hardcoded value. You don't have to worry on updating the cell when the screen rotates.

if (indexPath.row == <row number>) {
    cell.separatorInset = UIEdgeInsetsMake(0, INFINITY, 0, 0);
}
Reprise answered 29/7, 2015 at 4:55 Comment(1)
Be warned: Using INFINITY causes a runtime exception on iOS9Hoary
P
1

My requirement was to hide the separator between 4th and 5th cell. I achieved it by

    -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 3)
    {
        cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
    }
}
Pedology answered 12/1, 2016 at 6:56 Comment(0)
K
1

As (many) others have pointed out, you can easily hide all UITableViewCell separators by simply turning them off for the entire UITableView itself; eg in your UITableViewController

- (void)viewDidLoad {
    ...
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    ...
}

Unfortunately, its a real PITA to do on a per-cell basis, which is what you are really asking.

Personally, I've tried numerous permutations of changing the cell.separatorInset.left, again, as (many) others have suggested, but the problem is, to quote Apple (emphasis added):

"...You can use this property to add space between the current cell’s contents and the left and right edges of the table. Positive inset values move the cell content and cell separator inward and away from the table edges..."

So if you try to 'hide' the separator by shoving it offscreen to the right, you can end up also indenting your cell's contentView too. As suggested by crifan, you can then try to compensate for this nasty side-effect by setting cell.indentationWidth and cell.indentationLevel appropriately to move everything back, but I've found this to also be unreliable (content still getting indented...).

The most reliable way I've found is to over-ride layoutSubviews in a simple UITableViewCell subclass and set the right inset so that it hits the left inset, making the separator have 0 width and so invisible [this needs to be done in layoutSubviews to automatically handle rotations]. I also add a convenience method to my subclass to turn this on.

@interface MyTableViewCellSubclass()
@property BOOL separatorIsHidden;
@end

@implementation MyTableViewCellSubclass

- (void)hideSeparator
{
    _separatorIsHidden = YES;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (_separatorIsHidden) {
        UIEdgeInsets inset = self.separatorInset;
        inset.right = self.bounds.size.width - inset.left;
        self.separatorInset = inset;
    }
}

@end

Caveat: there isn't a reliable way to restore the original right inset, so you cant 'un-hide' the separator, hence why I'm using an irreversible hideSeparator method (vs exposing separatorIsHidden). Please note the separatorInset persists across reused cells so, because you can't 'un-hide', you need to keep these hidden-separator cells isolated in their own reuseIdentifier.

Kamikamikaze answered 10/8, 2016 at 2:5 Comment(0)
C
1

Inside the tableview cell class. put these line of code

separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: self.bounds.size.width)
Colonial answered 9/6, 2018 at 5:51 Comment(1)
Does not account for device/scene layout changes.Bernetta
H
1

For those looking specifically for hiding separator line of an Eureka row, this is the only solution that worked for me:

     row.cellUpdate { (cell, row) in
            cell.separatorInset =  UIEdgeInsets(top: 0, left: 0, bottom: 0, right: CGFloat.greatestFiniteMagnitude)
        }
Huba answered 4/4, 2020 at 15:16 Comment(0)
S
0
in viewDidLoad() {    

   tableView.separatorStyle = UITableViewCellSeparatorStyle.None 

}
Sonia answered 13/1, 2016 at 18:53 Comment(2)
Please elaborate on how this code answers the question.Mudslinger
This removes separators for the whole table, not specific cellsHorseback
U
0

On iOS9 i had the problem that changing the separator insets also effects the positioning of the text- and detailLabel.

I solved it with this

override func layoutSubviews() {
    super.layoutSubviews()

    separatorInset = UIEdgeInsets(top: 0, left: layoutMargins.left, bottom: 0, right: width - layoutMargins.left)
}
Uninspired answered 12/8, 2016 at 9:24 Comment(1)
Not work with UITableViewCell class - TextLabel and DetailedTextLabel move away from cell.Croom
E
0

Swift:

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

    ...

    // remove separator for last cell
    cell.separatorInset = indexPath.row < numberOfRowsInSection-1
        ? tableView.separatorInset
        : UIEdgeInsets(top: 0, left: tableView.bounds.size.width, bottom: 0, right: 0)

    return cell
}

Objective-C:

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    // remove separator for last cell
    cell.separatorInset = (indexPath.row < numberOfRowsInSection-1)
        ? tableView.separatorInset
        : UIEdgeInsetsMake(0.f, tableView.bounds.size.width, 0.f, 0.f);

    return cell;
}
Elise answered 31/3, 2017 at 13:27 Comment(0)
T
0

The code that all the answers have will make the cells padding equal to zero instead of the default value. I saw the problem in iOS 11 iPad Pro 12''

But I have one solution ("dirty hack") that is to make an empty section that will make separator line to hide.

Here is the code I used:

typedef enum PXSettingsTableSections {
    PXSettingSectionInvite = 0,
    PXSettingSectionAccount,
    PXSettingSectionPrivacy,
    PXSettingSectionCreation,
    PXSettingSectionTest,
    PXSettingSectionAboutHide,  // invisble section just to hide separator Line
    PXSettingSectionFooterHide, // invisble section just to hide separator Line
    PXSettingSectionNumItems,
} PXSettingsTableSectionsType;


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return PXSettingSectionNumItems;
}


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

    switch (section) {
        case PXSettingSectionInvite: return 1;
        case PXSettingSectionAccount:return (isSocialLogin) ? 1 : 2;
        case PXSettingSectionPrivacy: return 1;
        case PXSettingSectionCreation: return 2;
        case PXSettingSectionTest: return 3;
        case PXSettingSectionAboutHide: return 3;
        default: return 0;
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch(section)
    {
        case PXSettingSectionInvite: return nil;
        case PXSettingSectionAccount: return @"Account";
        case PXSettingSectionPrivacy: return @"Privacy";
        case PXSettingSectionCreation: return @"Someting";
        case PXSettingSectionTest: return @"Test";
        case PXSettingSectionAboutHide: return @" ";
        case PXSettingSectionFooterHide: return @" ";
    }
    return nil;
}


- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {

    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    if (section == PXSettingSectionFooterHide || section == PXSettingSectionAboutHide) {
        // [UIColor clearColor] will not work 
        [header.contentView setBackgroundColor:[UIColor whiteColor]];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // You can control here the size of one specific section
    if(section == PXSettingSectionAboutHide){
        return 0.0000001; //make it real small
    }
    return 45.0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    switch(indexPath.section)
    {
        case PXSettingSectionInvite:
            return self.inviteCell;
        case PXSettingSectionAccount:
            if (isSocialLogin) {
                return self.myWalletCell;
            }
            switch(indexPath.row)
            {
                case 0: return self.changePasswordCell;
                case 1: return self.myWalletCell;
            }
        case PXSettingSectionPrivacy:
            switch(indexPath.row)
        {
            case 0: return self.privateAccountCell;
        }
        case PXSettingSectionCreation:
            switch(indexPath.row)
        {
            case 0: return self.videoResolutionCell;
            case 1: return self.selfieMirrorCell;
        }
        case PXSettingSectionTest:
            switch(indexPath.row)
        {
            case 0: return self.termsOfUseImageCell;
            case 1: return self.attributionCell;
            case 2: return self.aboutCell;
        }
        case PXSettingSectionAboutHide:{
            switch(indexPath.row)
            {
                case 0: return self.clearCacheCell;
                case 1: return self.feedbackCell;
                case 2: return self.logoutCell;
            }
        }
    }

    return self.emptyCell;
}
Thegn answered 10/5, 2018 at 14:11 Comment(0)
W
0

The only solution that I get to work is the next one:

extension UITableViewCell {
    func separator(hide: Bool) {
        separatorInset.left = hide ? self.bounds.width * 1.5 : 16 // or whatever you want to be the left inset
    }
}

I don't know why, but self.bounds.width is not working as expected, so I multiplied by 1.5.

If you want to hide a cell you just need to do this:

cell.separator(hide: true)

And for the rest of the cells just send the parameter as false

cell.separator(hide: false)
Westerman answered 16/12, 2021 at 9:0 Comment(0)
S
-2

The width of the iphone is 320 . So put left and right value in Cell attribute for separatorInset more than half of 320 .

Shinny answered 27/8, 2014 at 7:27 Comment(1)
that's not working if app is for ipad or for iPhone 6 or 6+.Mono
G
-2

It work for me when I use extension and call within layoutSubviews() for update layout views immediately.

extension UITableViewCell {

    func removeSeparator() {
        separatorInset = UIEdgeInsetsMake(0, bounds.size.width, 0, 0)
    }
}

override func layoutSubviews() {
    super.layoutSubviews()

    removeSeparator()
}
Guildsman answered 22/3, 2018 at 7:49 Comment(0)
S
-3
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
Suzan answered 18/10, 2014 at 23:2 Comment(1)
Completely hides the cell separators for the entire table.Emission

© 2022 - 2025 — McMap. All rights reserved.