iOS 发现导航条上按钮的一个bug

本文探讨了在Xcode 11.7下,使用UIButton和UIControl创建自定义导航条按钮时遇到的问题。在不同iOS版本(如iOS12.4.4和iOS13.7)上,UIButton的高度会被自动调整,导致显示不一致,而UIControl则能保持预期的尺寸。因此,当需要设置背景颜色且要求精确尺寸时,推荐使用UIControl。
摘要由CSDN通过智能技术生成

0x00 自定义

导航条上的按钮,可以通过自定义视图的方式来创建
然而,有趣的事情发生了…

测试环境:
Xcode: Version 11.7 (11E801a)
真机


0x01 通过 UIButton 创建

直接上代码:

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 40, 25);
        button.layer.cornerRadius = 12.5;
        button.backgroundColor = [UIColor brownColor];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitle:@"中秋" forState:0];
        [button setTitleColor:[UIColor whiteColor] forState:0];
        button;
    })];

效果是这样的:

5s,iOS12.4.4
在这里插入图片描述

Xr,iOS13.7
在这里插入图片描述
代码中按钮的高度设置的是 25
然而,实际效果却被改变成 29
这特么的,蛋疼Q_Q


0x02 通过 UIControl 创建

直接上代码:

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:({
        
        UIControl *control = [[UIControl alloc] init];
        control.frame = CGRectMake(0, 0, 40, 25);
        control.layer.cornerRadius = 12.5;
        control.backgroundColor = [UIColor orangeColor];
        
        UILabel *label = [[UILabel alloc] init];
        label.frame = control.bounds;
        label.text = @"快乐";
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        [control addSubview:label];
        
        control;
    })];

效果是这样的:

5s,iOS12.4.4
在这里插入图片描述
Xr,iOS13.7
在这里插入图片描述
这回算是正确了 😃 😉


0x03 总结一下

如果要设置按钮的背景颜色
UIButton 就有可能不满足需要
除非最小高度是 29
否则,还是使用 UIControl


五笔学习-86版98版

就是这么简单~
在这里插入图片描述


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪冷啊

你的鼓励是对我的认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值