使用unbutton控件创建的对象,如果需要同时设置图片和文字的话,系统默认的式样是左图右字
比如
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:@"ico_st@3x"] forState:UIControlStateNormal];
[btn setTitle:@"哈哈" forState:UIControlStateNormal];
btn.frame = CGRectMake(100, 250, 100, 100);
btn.backgroundColor = [UIColor redColor];
[self.view addSubview:btn];
得到的按钮如图所示
但是,有的时候,我们需要的按钮需要其他的样式,比如,图片在上,文字在下
有许多同仁发帖所示的方法是是通过设置button.imageEdgeInset
但是,使用这个属性并不那么容易控制
我们可以通过使用自定义按钮来实现这个效果
代码如下:
创建一个类,继承于uibutton,明明为MyButton
MyButton.h
#import <UIKit/UIKit.h>
@interface MyButton : UIButton
@property(nonatomic,assign)CGRect imgRect;
@property(nonatomic,assign)CGRect titleRect;
-(instancetype)initWithtype:(UIButtonType)type WithFrame:(CGRect)frame WithImgRect:(CGRect)imgRect WithTitleRect:(CGRect)titleRect;
@end
MyButton.m
#import "MyButton.h"
@implementation MyButton
-(instancetype)initWithtype:(UIButtonType)type WithFrame:(CGRect)frame WithImgRect:(CGRect)imgRect WithTitleRect:(CGRect)titleRect{
self = [MyButton buttonWithType:type];
if (self) {
self.frame = frame;
self.imgRect = imgRect;
self.titleRect = titleRect;
}
return self;
}
-(CGRect)imageRectForContentRect:(CGRect)contentRect{
return self.imgRect;
}
-(CGRect)titleRectForContentRect:(CGRect)contentRect{
return self.titleRect;
}
@end
在需要使用的地方调用
CGRect r1 = CGRectMake(10, 80, 80, 20);
CGRect r2 = CGRectMake(20, 10, 60, 60);
MyButton * button = [[MyButton alloc] initWithtype:UIButtonTypeCustom WithFrame:CGRectMake(100, 100, 100, 100) WithImgRect:r2 WithTitleRect:r1];
[button setTitle:@"哈哈" forState:UIControlStateNormal];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setImage:[UIImage imageNamed:@"ico_st@3x"] forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
即可实现如第二张图的效果