UIButton的背景图片

一直在使用UIButton创建按钮,包括Plain纯文字型的按钮、设置背景图片、设置选中状态图片按钮…特别是当我们的提供的图片比按钮本身的尺寸小时,会导致按钮没有被图片完全填充,当图片比button大时,图片会超出button的frame范围(除非设置button.layer.maskToBounds = YES可防止超出button的frame)。其实UIButton已经提供了给我们自由定制button的接口,只是很多人都没有注意到它的存在。我们只要继承UIButton类,然后在其子类中重写下面的几个方法中的一个或者几个,便可以自由控制UIButton中的image、label等的位置。

// these return the rectangle for the background (assumes bounds), the content (image + title) and for the image and title separately. the content rect is calculated based
// on the title and image size and padding and then adjusted based on the control content alignment. there are no draw methods since the contents
// are rendered in separate subviews (UIImageView, UILabel)

- (CGRect)backgroundRectForBounds:(CGRect)bounds;
- (CGRect)contentRectForBounds:(CGRect)bounds;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

猜你喜欢

转载自www.cnblogs.com/weixiaochao/p/8975305.html