Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding padding to an UIView

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.

like image 421
Meda Avatar asked Feb 13 '13 15:02

Meda


People also ask

How do I add padding to UILabel?

If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.

What is layout margins in Swift?

The layout margins consist of inset values for each edge (top, bottom, leading, and trailing) of the view. These inset values create a space between the edges of the view's bounds rectangle and the content inside the view. The following image shows two views with different sets of layout margins.

What is UIEdgeInsets?

UIEdgeInsets encapsulates four different CGFloat values for the inset values of the top, left, bottom, and right (respectively) individually. Positive inset values shrink the content area, while negative inset values will effectively increase it.


2 Answers

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); 
like image 92
George Green Avatar answered Oct 14 '22 19:10

George Green


Update for Swift 3

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

:)

like image 32
Marcus Vinicius Kuquert Avatar answered Oct 14 '22 19:10

Marcus Vinicius Kuquert