I'm looking for a way to add a padding property to an UIView. Ideally, I would like to avoid subclassing and putting it in a category. The usage would be something like:

myview.padding = UIEdgeInsetsMake(10, 10, 10, 10);

And maybe have a paddingBox property as well which would return a CGRect describing the size and position of the inner padding box.

Now, how would one implement in a category something like that. I initially though of using bounds, but unfortunately the size of the bounds is linked to the size of the frame (always the same) only the coordinates can differ.


Solution 1:

This is generally done by setting the bounds within the view. So if you wanted an inset of 10 all round you could do:

view.bounds = CGRectInset(view.frame, 10.0f, 10.0f);

The bounds defines the drawable area of the view, relative to the frame. So this should give in effect a padding. You can then get the 'paddingBox' just from the bounds.

Hope this helps! :)

Update in Swift 5+, It's

view.bounds = view.frame.insetBy(dx: 10.0, dy: 10.0);

Solution 2:

Update for Swift 3

view.bounds = view.frame.insetBy(dx: 10.0, dy: 10.0)

:)

Solution 3:

Update: Since iOS11 you should use directionalLayoutMargins instead of layoutMargins.

Source: https://developer.apple.com/documentation/uikit/uiview/1622566-layoutmargins?language=objc

Since iOS 8, each view has now a layoutMargins property which corresponds to the padding.

myview.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10);

When you use AutoLayout, a format with |-[subview]-|, |- will refer to the edges defined with layoutMargins.

Source: https://developer.apple.com/reference/uikit/uiview/1622566-layoutmargins?language=objc