定制UIButton中文字和图片的位置

18 篇文章 0 订阅

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];
}
测试结果如图:

完成,至于自己想要将文字和图片放在什么位置,自己随意,代码很简单,不再多说。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值