设置UIButton上面是image,下面是title
此处写了一个UIButton的子类,添加了一个设置titleEdgeInsets和imageEdgeInsets
的方法,代码如下:
1 #import <UIKit/UIKit.h> 2 3 @interface UIButton_ImageAndTitle : UIButton 4 5 // space是图片与标题之间的间隙 6 - (void)setImageAndTitleEdgeInsets:(float)space; 7 8 @end
方法实现:
1 #import "UIButton_ImageAndTitle.h" 2 3 @implementation UIButton_ImageAndTitle 4 5 - (void)setImageAndTitleEdgeInsets:(float)space { 6 CGSize imageSize = self.imageView.frame.size; 7 CGSize titleSize = self.titleLabel.frame.size; 8 CGFloat totalHeight = (imageSize.height + titleSize.height + space); 9 10 self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; 11 12 [self setImageEdgeInsets:UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width)]; 13 [self setTitleEdgeInsets:UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height), 0.0*KSCALE_WIDTH)]; 14 } 15 16 @end
用的时候很简单:
1 self.btnFlash = [[UIButton_ImageAndTitle alloc] init]; 2 _btnFlash.bounds = CGRectMake(0, 0, size.width, size.height); 3 _btnFlash.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame) * 3/4, CGRectGetHeight(_bottomItemsView.frame)/2); 4 [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/scan_flash_default"] forState:UIControlStateNormal]; 5 [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/scan_flash_selected"] forState:UIControlStateSelected]; 6 [_btnFlash setTitle:@"打开手电筒" forState:UIControlStateNormal]; 7 [_btnFlash setImageAndTitleEdgeInsets:10*KSCALE_HEIGHT]; 8 [_btnFlash addTarget:self action:@selector(openOrCloseFlash:) forControlEvents:UIControlEventTouchUpInside];
我这里的效果如下:
posted on 2017-12-06 18:54 Walking_Jin 阅读(126) 评论(0) 编辑 收藏 举报