導覽列上的按鈕,可以通過自定義檢視的方式來建立
然而,有趣的事情發生了…
測試環境:
Xcode: Version 11.7 (11E801a)
真機
直接上程式碼:
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
直接上程式碼:
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
這回算是正確了 😃 😉
如果要設定按鈕的背景顏色
UIButton
就有可能不滿足需要
除非最小高度是 29
否則,還是使用 UIControl
吧
就是這麼簡單~