向 UIView 添加填充 [英] Adding padding to an UIView

查看:28
本文介绍了向 UIView 添加填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种向 UIView 添加 padding 属性的方法.理想情况下,我想避免子类化并将其放在一个类别中.用法类似于:

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);

也许还有一个 paddingBox 属性,它会返回一个 CGRect 描述内部填充框的大小和位置.

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

现在,如何在一个类别中实现类似的东西.我最初虽然使用 bounds,但不幸的是 bounds 的大小与 frame 的大小有关(始终相同),只有坐标可以不同.

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.

推荐答案

这通常是通过在视图中设置边界来完成的.所以如果你想要一个 10 的插入,你可以这样做:

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);

边界定义了视图的可绘制区域,相对于框架.所以这实际上应该提供一个填充.然后,您可以从边界获取paddingBox".

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.

希望这有帮助!:)

Swift 5+ 中的更新,它是

Update in Swift 5+, It's

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

这篇关于向 UIView 添加填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆