Adding additions to UIView

I am looking for a way to add a padding property to a UIView. Ideally, I would like to avoid subclassing and put it in a category. Usage will be something like this:

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

And perhaps it also has a paddingBox property that returns a CGRect describing the size and position of the internal padding field.

Now, how would I implement something similar in the category. At first I used bounds , but, unfortunately, the size of bounds is related to the size of the frame (always the same), only the coordinates can differ.

+58
ios iphone cocoa-touch uikit uiview
Feb 13 '13 at 15:21
source share
7 answers

This is usually done by setting boundaries in the view. So if you want to insert 10 rounds, you can do:

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

Borders define the scope related to the image relative to the frame. Therefore, this should lead to filling. Then you can get the "paddingBox" only from the borders.

Hope this helps! :)

+44
Feb 13 '13 at 15:46
source share

Update for Swift 3

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

:)

+27
Jan 31 '17 at 21:34
source share

Starting with iOS 8, each view is now the layoutMargins property of the layoutMargins that corresponds to the fill.

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

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

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

+17
Jan 31 '17 at 21:41
source share

What you really need to do is create a view and add a subtitle to it. Make one kind of background and give it the desired frame. Then make the second subquery the frame you want using the edges.

 UIView backgroundView = new UIView(CGRect.FromLTRB(0, 0, 100, 100)) { BackgroundColor = backgroundGray, }; //Will have a right edge inset of 10 UIView edgyView = new UIView(CGRect.FromLTRB(0, 0, 90, 100)) { BackgroundColor = backgroundGray, } backgroundView.AddSubview(edgyView); 
+8
May 01 '15 at 23:14
source share

You can override the alignmentRectInsets property. Here is an example in Swift 4

 class YourCustomView: UIView { override var alignmentRectInsets: UIEdgeInsets { return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } } 
+8
Nov 27 '17 at 16:19
source share

Update for Swift 4:

 self.yourView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) 
+1
Mar 13 '19 at 15:59
source share

You can insert the frame / borders of the view as follows:

  yourView.frame = yourView.frame.inset(by: UIEdgeInsets(top: .zero, left: 5.0, bottom: 5.0, right: .zero) 
0
Jun 25 '19 at 3:24
source share



All Articles