Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView left and right padding

I have table view. In it I have section, each section has one row only. I use the sections so that I can control the space between the rows with header height. I would like to add padding to UITableView so that I can space the cells/sections from the edges of the device. The spacing needs to have the color of the UITableView background.

like image 972
h3dkandi Avatar asked May 31 '16 09:05

h3dkandi


2 Answers

Subclass UITableviewCell and override setFrame method of it like,

- (void)setFrame:(CGRect)frame {
    frame.origin.x += inset;
    frame.size.width -= 2 * inset;
    [super setFrame:frame];
}

So, it will make padding of two pixel from left and right side. you can change it as per requirement.

You can use contentInset but it is work only for vertical spacing (top and bottom). You should setFrame of cell as mentioned above for horizontal spacing.

You can take this answer and this answer as a reference.

Hope this will help :)

like image 186
Ketan Parmar Avatar answered Nov 02 '22 14:11

Ketan Parmar


As Lion has been mention! His method is working fine but it's in objectiveC. Here is the method for swift 4.2

override var frame: CGRect {
        get {
            return super.frame
        }
        set (newFrame) {
            var frame = newFrame
            frame.origin.x += 10
            frame.size.width -= 2 * 10
            super.frame = frame
        }
    }
like image 34
Anonymous-E Avatar answered Nov 02 '22 16:11

Anonymous-E