Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom separator insets on UITableViewCell

In my UITableView 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:

Separator

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 UIEdgeInset.zero

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

Any helps?

like image 443
donadev Avatar asked Nov 22 '16 14:11

donadev


2 Answers

Basically, that first piece of code is correct for setting the separator inset, color and style which is:

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

And the one at cell's separatorInset is for the cell's content. So I'm confused of what you actually want to achieve here. From your last phrase, your content was shrunk and that was caused by 'cell.separatorInset = separatorInset' and you somehow don't want that.

So I suggest that you remove this line of code:

cell.separatorInset = separatorInset
like image 68
NFerocious Avatar answered Nov 15 '22 05:11

NFerocious


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.

like image 30
Ali Omari Avatar answered Nov 15 '22 04:11

Ali Omari