我的UIToolbar
中有一个标题为Done的UIBarButtonItem
。现在我想用粗体将字体从默认字体改为"Trebuchet MS"。我该怎么做呢?
发布于 2012-01-13 19:37:20
因为UIBarButtonItem继承自UIBarItem,所以您可以尝试
- (void)setTitleTextAttributes:(NSDictionary *)attributes
forState:(UIControlState)state
但这仅适用于iOS5。对于iOS 3/4,您必须使用自定义视图。
发布于 2012-10-02 05:15:46
准确地说,这可以按如下方式完成
[buttonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica-Bold" size:26.0], NSFontAttributeName,
[UIColor greenColor], NSForegroundColorAttributeName,
nil]
forState:UIControlStateNormal];
或者使用object字面语法:
[buttonItem setTitleTextAttributes:@{
NSFontAttributeName: [UIFont fontWithName:@"Helvetica-Bold" size:26.0],
NSForegroundColorAttributeName: [UIColor greenColor]
} forState:UIControlStateNormal];
为了方便起见,下面是Swift的实现:
buttonItem.setTitleTextAttributes([
NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 26.0)!,
NSAttributedStringKey.foregroundColor: UIColor.green],
for: .normal)
发布于 2013-04-29 12:02:25
对于那些对在整个应用程序中使用UIAppearance
来设置UIBarButtonItem
字体样式感兴趣的人,可以使用下面这行代码来完成:
目标C:
NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:12.0], NSForegroundColorAttributeName: [UIColor whiteColor]};
[[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];
Swift 2.3:
UIBarButtonItem.appearance().setTitleTextAttributes(
[
NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
NSForegroundColorAttributeName : UIColor.white
],
for: .normal)
Swift 3
UIBarButtonItem.appearance().setTitleTextAttributes(
[
NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
NSForegroundColorAttributeName : UIColor.white,
], for: .normal)
Swift 4
UIBarButtonItem.appearance().setTitleTextAttributes(
[
NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Light", size: 12)!,
NSAttributedStringKey.foregroundColor : UIColor.white,
], for: .normal)
或者对于单个UIBarButtonItem (不是所有的应用程序),如果你有一个特别的按钮的自定义字体:
Swift 3
let barButtonItem = UIBarButton()
barButtonItem.setTitleTextAttributes([
NSFontAttributeName : UIFont(name: "FontAwesome", size: 26)!,
NSForegroundColorAttributeName : UIColor.white,
], for: .normal)
barButtonItem.title = "\u{f02a}"
Swift 4
let barButtonItem = UIBarButton()
barButtonItem.setTitleTextAttributes([
NSAttributedStringKey.font : UIFont(name: "FontAwesome", size: 26)!,
NSAttributedStringKey.foregroundColor : UIColor.white,
], for: .normal)
barButtonItem.title = "\u{f02a}"
当然,你可以随心所欲地改变字体和大小。我更喜欢将此代码放在didFinishLaunchingWithOptions
部分的AppDelegate.m
文件中。
可用属性(只需将它们添加到NSDictionary
):
使用UIFont
NSForegroundColorAttributeName
:更改字体使用UIColor
NSShadow
:更改颜色添加下拉阴影(参见NSShadow
class reference)(针对iOS7+更新)
https://stackoverflow.com/questions/8849913
复制相似问题