Any way to horizontally inset the cells of a UITableView?

Howdy,

Is it possible to inset the left and right edges of the cells contained within a UITableView? I initially thought that contentInsets would do the trick, but I can't to get this to work. More specifically, it seems that adjusting the contentInsets only affects the scrollable area rather than the area actually occupied by the cells. Are the cells not a part of the content?

The only other way I can think of doing this is by embedding the UITableView inside another UIScrollView, which feels like overkill. Is there a better way? Note that I do not want to adjust the bounds of the UITableView because I want the area occupied by the insets to remain scrollable.

Thanks,

smkuehnhold

Accepted Reply

When using the .insetGrouped style, cells are inset on the leading & trailing edges from the table view by the leading and trailing values of the UITableView's directionalLayoutMargins. You can set custom layout margins on the table view to adjust the amount of these insets.

  • I have just noticed that the directional layout margins are being reset from my custom specified to (top: 0.0, leading: 20.0, bottom: 0.0, trailing: 20.0) sometime after my view controller is loaded. Do you happen to know what could be causing this behavior?

    This seems to occur sometime inbetween calls to viewWillAppear(:animated) and viewDidAppear(:aniamted)

Add a Comment

Replies

When using the .insetGrouped style, cells are inset on the leading & trailing edges from the table view by the leading and trailing values of the UITableView's directionalLayoutMargins. You can set custom layout margins on the table view to adjust the amount of these insets.

  • I have just noticed that the directional layout margins are being reset from my custom specified to (top: 0.0, leading: 20.0, bottom: 0.0, trailing: 20.0) sometime after my view controller is loaded. Do you happen to know what could be causing this behavior?

    This seems to occur sometime inbetween calls to viewWillAppear(:animated) and viewDidAppear(:aniamted)

Add a Comment

In the case of a custom cell, you could put your own view inside the cell's contentView, and add AutoLayout to inset your desired number of pixels. Then make the cells contentView.backgroundColor = .clear, and if needed also set the cell.backgroundColor = .clear. That should do the trick.

Happy Coding! Wouter