UIbutton设置图片和文字

博客围绕Button上添加图片和文字时,对titleEdgeInsets和imageEdgeInsets属性的使用展开。介绍了UIEdgeInsets参数含义,通过代码示例展示设置过程中遇到的文字显示及居中问题,摸索出先根据图片设置文字、再设置图片的解决方法,指出设置与图片像素有关,多Button时最好保证图片像素一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址::https://www.jianshu.com/p/65d559614efc

 

根据需求,有时候需要在button上添加图片和文字,这就需要用到buttontitleEdgeInsetsimageEdgeInsets属性。用一个还好,但同时使用这2个就感觉控制不好,很多时候title在图片下面但不能居中。困扰已久,今天研究了一下,总结一下。


UIEdgeInsets

typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;

里面的四个参数表示距离上边界、左边界、下边界、右边界的距离,默认都为零,title/image在button的正中央


先上代码 , 使用的图片的像素是55 * 55

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor orangeColor];
    btn.frame = CGRectMake(100, 100, 80, 80);
    [btn setImage:[UIImage imageNamed:@"致电我们-图标"] forState:0];
    [btn setTitle:@"1234" forState:0];
    [btn setTitleColor:[UIColor whiteColor] forState:0];
    
    [btn setImageEdgeInsets:UIEdgeInsetsMake(5, 25, 45, 25)];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(50, 0, 5, 0)];
    
    [self.view addSubview:btn];

定义了一个btn,以为可以显示正确的button,运行一看我错了。文字显示不出来。

9E93E830-8405-473C-A364-E7397DA5D971.png

经过反复的测试,发现设置成

[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, -55, 5, 0)];

刚好可以使文字居中且显示出来;但问题又来了,图片的像素一变,文字又跑其他地方去了。所以摸索出最终的解决方法:先根据图片设置文字,再设置图片(前提是图片的像素要比button的像素小,不然还是得按图片的真是像素来)

[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, -btn.imageView.bounds.size.width, 5, 0)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(5, 25, 45, 25)];

200C4F64-A9CE-402B-90DB-3652DC6D78FD.png


同理如果图片和文字左右显示

直接上代码

    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.backgroundColor = [UIColor orangeColor];
    btn1.frame = CGRectMake(100, 250, 100, 60);
    [btn1 setImage:[UIImage imageNamed:@"致电我们-图标"] forState:0];
    [btn1 setTitle:@"电话" forState:0];
    [btn1 setTitleColor:[UIColor whiteColor] forState:0];
   
    [btn1 setTitleEdgeInsets:UIEdgeInsetsMake(15, -btn1.imageView.bounds.size.width + 40, 15, 0)];
    [btn1 setImageEdgeInsets:UIEdgeInsetsMake(10, 5, 10, 55)];   //40 * 40
    
    [self.view addSubview:btn1];

显示

 

7AB616A1-1BB8-4CB2-BC5A-3FD59A7B16A4.png


总结

总之,设置button的这两个属性时,与图片的真实像素有关。如果多个button的话,最好保证图片像素是一样的。

 



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值