关于UIbutton的titleEdgeInsets和imageEdgeInsets的一些看法

本文介绍如何在iOS开发中精确调整UIButton上标题的位置及内边距,通过使用`titleRectForContentRect`方法和`UIEdgeInsetsMake`函数实现按钮标题与图片之间的布局控制。

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

UIEdgeInsets —>titleEdgeInsets

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];

    button.backgroundColor = [UIColor blueColor];

    button.frame = CGRectMake(50, 100, 200, 40);

    [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];

    [button setTitle:@"返回" forState:(UIControlStateNormal)];

    [button setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];

    [self.view addSubview:button];

    button.titleLabel.backgroundColor = [UIColor redColor];

    

    // 这里必须使用titleRectForContentRect这个方法

    // 之前使用button.titleLabel.frame时,size0,x值也不准确,不知道为什么(好像多了图片的宽度)

    CGRect tmpRect = [button titleRectForContentRect:button.bounds];

    CGFloat width = tmpRect.size.width;

    CGFloat label_X = tmpRect.origin.x;

    

    /**

     UIEdgeInsetsMake

     

     @param top 距离顶部偏移量

     @param left 距离左边偏移量        正数x表示:距离左边距离增加x,即向下偏移 x / 2.0,还不知道为什么会这样,其他同理

     @param bottom 距离底部偏移量      只测试了左右,上下没测,应该同理

     @param right 距离右边偏移量

     @return UIEdgeInsets

     */

    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, (200.0 - width - label_X) * 2, 0, 0)];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值