1、与文字和图片位置相关的函数:
2、定义一个MyButton类,继承自UIButton
//
// MyButton.m
#import "MyButton.h"
@implementation MyButton
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}
return self;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
return CGRectMake(0, contentRect.size.height / 5 * 3, contentRect.size.width, contentRect.size.height / 5 * 2);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat width = contentRect.size.width;
CGFloat height = contentRect.size.height;
return CGRectMake(width / 5, height / 10, width / 5 * 3, height / 5 * 3 - height / 10 * 2);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
3、测试,定义一个MyButton对象,设置文字和图片
#import "ViewController.h"
#import "MyButton.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
CGRect rect = CGRectMake(20, 100, 150, 150);
MyButton * btn = [[MyButton alloc] initWithFrame:rect];
[btn setTitle:@"mybtn" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:btn];
[btn setImage:[UIImage imageNamed:@"apple.jpg"] forState:UIControlStateNormal];
btn.titleLabel.backgroundColor = [UIColor blueColor];
}
测试结果如图:
完成,至于自己想要将文字和图片放在什么位置,自己随意,代码很简单,不再多说。