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版
就是这么简单~