UIbutton设置图片和文字

    xiaoxiao2022-07-05  164

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

     

    根据需求,有时候需要在button上添加图片和文字,这就需要用到button的titleEdgeInsets和imageEdgeInsets属性。用一个还好,但同时使用这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的话,最好保证图片像素是一样的。

     

     

    最新回复(0)