How do I adjust the left margin for prototype cells in a UITableView?

If I create a UITableViewController, for example via File → New Project... → iOS → Master-Detail Application in Xcode, a UITableView is created with a prototype cell.

The generated view hierarchy is:

UITableViewController view hierarchy

A left "margin" is automagically created between the Cell's Content UIView left edge and the "Title" text's UILabel element as shown below in orange.

Prototype cell gap

This results in a corresponding margin between the device's screen edge and the UILabel text at runtime:

Runtime gap

So, where is the width of this gap set, and how can it be adjusted?

The controls in the Size Inspector for the UILabel are greyed out:

enter image description here

My preferred option would to be able to set the width of this gap from within Interface Builder, but I would also like to understand where this gap is being set, and how to alter it programmatically.


You just need to set contentInset property of the table view. You can set value according to your need.

self.tableView.contentInset = UIEdgeInsetsMake(0, -15, 0, 0);

OUTPUT RESULT


Go to Main.storyboard > select the UITableViewCell > Attributes Inspector. Change Separator dropdown list from Default Insets to Custom Insets. Change the left inset from 15 to 0

enter image description here


Starting from iOS 8 is available the cell property layoutMargins. So the correct way to adjust cell margins is setting this property in your tableView:cellForRowAtIndexPath or in your custom UITableViewCell in this way:

override func awakeFromNib() {
    super.awakeFromNib()

    self.layoutMargins = UIEdgeInsetsZero //or UIEdgeInsetsMake(top, left, bottom, right)
    self.separatorInset = UIEdgeInsetsZero //if you also want to adjust separatorInset
}

I hope this can help someone.