我找不到在自定义中设置标题字体大小的方法UIBarButtonItem
。我能想到的唯一方法是将其设置为图像,我想避免这种情况。还有其他建议吗?
问问题
28940 次
6 回答
82
目标-C:
NSUInteger fontSize = 20;
UIFont *font = [UIFont boldSystemFontOfSize:fontSize];
NSDictionary *attributes = @{NSFontAttributeName: font};
UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
[item setTitle:@"Some Text"];
[item setTitleTextAttributes:attributes forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = item;
迅速:
let fontSize:CGFloat = 20;
let font:UIFont = UIFont.boldSystemFont(ofSize: fontSize);
let attributes:[String : Any] = [NSFontAttributeName: font];
let item = UIBarButtonItem.init();
item.title = "Some Text";
item.setTitleTextAttributes(attributes, for: UIControlState.normal);
self.navigationItem.rightBarButtonItem = item;
于 2012-07-07T21:07:54.520 回答
3
创建一个 UILabel 并使用-initWithCustomView:
.
于 2010-04-27T13:27:10.623 回答
3
作为kennytm 建议的具体示例,您可以UIBarButtonItem
使用以下内容创建:
UILabel *txtLabel = [[UILabel alloc] initWithFrame:rect];
txtLabel.backgroundColor = [UIColor clearColor];
txtLabel.textColor = [UIColor lightGrayColor];
txtLabel.text = @"This is a custom label";
UIBarButtonItem *btnText = [[[UIBarButtonItem alloc] initWithCustomView:txtLabel] autorelease];
然后,您可以将其添加为 a 上的居中文本UIToolbar
,例如:
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:rect];
toolBar.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *flexSpace1 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
UIBarButtonItem *flexSpace2 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
[toolBar setItems:[NSArray arrayWithItems:flexSpace1, btnText, flexSpace2, nil]];
(当然,为了获得正确的格式,rect
用于初始化txtLabel
并且toolBar
应该是正确的大小......但这是另一个练习。)
于 2012-03-10T20:08:45.587 回答
2
[[UIBarButtonItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
[UIFont fontWithName:@"FONT-NAME" size:21.0], NSFontAttributeName, nil]
forState:UIControlStateNormal];
于 2015-02-03T13:38:30.617 回答
2
斯威夫特5:
let item = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(self.onItemTapped))
let font:UIFont = UIFont(name: "", size: 18) ?? UIFont()
item.setTitleTextAttributes([NSAttributedString.Key.font: font], for: UIControl.State.normal)
于 2020-02-27T22:11:02.073 回答
1
let barButtonItem: UIBarButtonItem = UIBarButtonItem(title: "Title",
style: .plain,
target: nil,
action: nil)
let font: UIFont = UIFont.systemFont(ofSize: 12.0)
let textAttributes: [NSAttributedString.Key: Any] = [.font: font]
barButtonItem.setTitleTextAttributes(textAttributes, for: .normal)
barButtonItem.setTitleTextAttributes(textAttributes, for: .selected)
于 2021-02-04T20:34:46.123 回答