iOS - 按钮[图上文下]的设置

内容不够,图来凑... 

一个工具类.h

@interface ZJJCustomButtonSubview : UIView

/**

使按钮子视图变为[图上文下]

@param button 要改变位置的按钮

@param insert_y 图片和文字的上下间距

*/

+ (void)zjjCustomButton:(UIButton *)button imageTitleInsert:(CGFloat)insert_y;

@end

扫描二维码关注公众号,回复: 4819442 查看本文章

工具类.m

+ (void)zjjCustomButton:(UIButton *)button imageTitleInsert:(CGFloat)insert_y {

    button.imageEdgeInsets = UIEdgeInsetsMake(-(button.titleLabel.frame.size.height+insert_y)/2,

                                              button.titleLabel.frame.size.width/2,

                                              (button.titleLabel.frame.size.height+insert_y)/2,

                                              -button.titleLabel.frame.size.width/2

                                              );

    button.titleEdgeInsets = UIEdgeInsetsMake((button.imageView.frame.size.height+insert_y)/2,

                                              -button.imageView.frame.size.width,

                                              -(button.imageView.frame.size.height+insert_y)/2,

                                              0

                                              );

}

本该到此结束,但...

1.为什么不用button.titleLabel.intrinsicContentSize代替button.titleLabel.frame.size,这是因为前者表示的是尺寸太准确了,当文字过多或者按钮过小的时候,就会发现问题,可以理解成期望尺寸.后者则表示实际的尺寸.

2.在调用该加号方法之前,一定要给button.imageView写点啥,比如:button.imageView.backgroundColor = [UIColor clearColor];

或者  button.imageView.hidden = NO;

否则,尺寸获取不到.至于为什么多这么一个操作,我特么还想知道呢...

猜你喜欢

转载自blog.csdn.net/Q_Q33757152/article/details/85999794