donadev donadev - 13 days ago 5
Swift Question

Set custom separator insets on UITableViewCell

In my

I want a 'centered' separator effect in which the separator is shrunk by 30pt from left and 30 from right.
I've managed to accomplish that from Interface Builder setting the 'Custom Insets' property of the TableView itself, but I cannot reproduce this behaviour by code (and I have to do that this way).

In particular, with this piece of code:

self.tableView.separatorColor = .green
self.tableView.separatorStyle = .singleLine
self.tableView.separatorInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)

And also this one:

@objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recent_cell") as! TPExpandableTableViewCell
//setting cell insets
cell.separatorInset = separatorInset
cell.item = items[indexPath.row]
return cell

I obtained the following output on the iPhone 6S Simulator:


Seems like that the separator content view get shrunk, but the separator background view gets not. I also tried to remove the line that sets the separatorInset of the cell, and the result was an inset equal to

I can confirm that the white line under the green on is a separator-related view, because if I change the separatorStyle to
, it disappears

Any helps?


The best approach to make custom separator is to disable UITableView separator and create a view inside the cell with the height you want such as 1px and then add the constraints to the view to be at center bottom of the cell.