Adding padding to an UIView

2019-02-01 16:29发布

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.

5条回答
\"骚年 ilove
2楼-- · 2019-02-01 16:34

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)
    }
}
查看更多
走好不送
3楼-- · 2019-02-01 16:41

Update for Swift 3

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

:)

查看更多
你好瞎i
4楼-- · 2019-02-01 16:42

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

查看更多
beautiful°
5楼-- · 2019-02-01 16:53

What you really have to do is create a view and add a subview to it. Make one view the background and give it the frame you want. Then make the second subview the frame you want with the edge insets.

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);
查看更多
够拽才男人
6楼-- · 2019-02-01 16:54

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! :)

查看更多
登录 后发表回答