UIButton - - 同时调整图片和标题的位置

一、直接通过以下几个属性进行设置
1 @property(nonatomic)      UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero
2 @property(nonatomic)          UIEdgeInsets imageEdgeInsets;                // default is UIEdgeInsetsZero 
如果同时设置图片和标题,会发现图片在左侧,标题在右侧,而一般情况下我们期望的是上图下字的布局。然后我们进入文档看到UIButton同提供了 以上两格字段来调整其内部布局:
1》按上左下右设置图片的位置(很好,很完美)
2》同样的按照上左下右设置标题label的位置,运行,我去label呢?怎么不见了???????
注意:后来才知道,默认的img和title 的布局是相互影响的,除了以上两格字段,UIButton中还有以下字段
1 @property(nonatomic)          UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero. On tvOS 10 or later, default is nonzero except for custom buttons.
系统默认的把 img+title 当成一个矩形框放到button的正中间(想一想xib中的约束,这里可以认为title左侧的约束是相对于img的右侧来赋值的)
 
title上下边界正常设置即可,对于左右的设置时需要注意,title左边界是以图片的右边为标准的如下图紫线

 

所以如果想让标题以button的左侧为标准    就要把线向左移动 ( img的左边距 + imgSize.width )
 
这一方法比较繁杂可以考虑第二种方法如下
二、自定义一个Button继承自UIButton
重写父类的方法
1、第一种:
// 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;

  - (CGRect)titleRectForContentRect:方法返回的是标题的frame

  - (CGRect)imageRectForContentRect:返回的是imageview的frame

  - (CGRect)contentRectForBounds:返回的是imageview+title的矩形框的frame

  - (CGRect)backgroundRectForBounds:返回的是背景图片的frame

  当然这里frame都是相对于bounds来说的

2、第二种:

重写- (void)layoutSubviews方法,因为改变frame的时候会调用layoutSubviews方法进行子控件的布局

posted @ 2017-09-18 11:26  熹微_念  阅读(820)  评论(0编辑  收藏  举报