【发布时间】:2010-04-27 11:34:27
【问题描述】:
我找不到在自定义UIBarButtonItem 中设置标题字体大小的方法。我能想到的唯一方法是将其设置为图像,我想避免这种情况。还有其他建议吗?
【问题讨论】:
-
这是一个类似的问题。 stackoverflow.com/questions/5421121/…
标签: ios uibarbuttonitem uifont
我找不到在自定义UIBarButtonItem 中设置标题字体大小的方法。我能想到的唯一方法是将其设置为图像,我想避免这种情况。还有其他建议吗?
【问题讨论】:
标签: ios uibarbuttonitem uifont
目标-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;
【讨论】:
UIAppearance代理setTitleTextAttributes。
创建一个 UILabel 并使用-initWithCustomView:。
【讨论】:
作为kennytm suggests 的具体示例,您可以使用以下内容创建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];
然后,您可以将其添加为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]];
(当然,为了获得正确的格式,用于初始化 txtLabel 和 toolBar 的 rect 应该是正确的大小......但这是另一个练习。)
【讨论】:
[[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];
【讨论】:
Swift5:
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)
【讨论】:
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)
【讨论】: