iOS UIBarButtonItem 上使用 FontAwesome

3

我正在尝试使用iOS FontAwesome在一个栏按钮上设置图标,如下所示:

[self.barButton setTitle:[NSString fontAwesomeIconStringForEnum:FACamera]];

以及这个:
[self.barButton setTitle:[NSString fontAwesomeIconStringForIconIdentifier:@"fa-camera"]];

无论我使用什么标识符,结果都是一样的: enter image description here 可能出了什么问题?

你是否将 FontAwesome.ttf 作为按钮的必要要求? - holex
@holex,不确定在哪里设置那个... - user623396
UIButton有一个font属性 - 这可能是一个好的开始,但原作者有一个详细的描述来展示你如何做到这一点 - 如果你已经阅读了文档... - holex
据我所知,UIBarButtonItem没有字体属性。(顺便说一句,不需要讽刺) - user623396
这是在苹果公司明确意见下的官方做法;不幸的是,在这里,IADO比IMHO更有说服力。 :) - holex
显示剩余6条评论
5个回答

5

如果其他人也有这方面的疑问:

[self.barButton setTitleTextAttributes:@{
                  NSFontAttributeName: [UIFont fontWithName:@"FontAwesome" size:24.0],
                  NSForegroundColorAttributeName: self.view.tintColor
                                         } forState:UIControlStateNormal]; 
[self.barButton setTitle:[NSString fontAwesomeIconStringForIconIdentifier:@"fa-camera"]];

2

在Swift中:

    let filterButton = UIBarButtonItem(title: String.fontAwesomeIconWithName(FontAwesome.Filter), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("filterClicked"))
    filterButton.setTitleTextAttributes(NSDictionary(dictionary: [NSFontAttributeName:UIFont.fontAwesomeOfSize(25), NSForegroundColorAttributeName : UIColor.COLOR_BLUE_DARK]), forState: UIControlState.Normal)

    self.navigationItem.rightBarButtonItem = filterButton

1
使用FontAwesomeKit 2.2 API,您可以像这样操作:
[self.barButton setTitleTextAttributes:@{
    NSFontAttributeName: [FAKFontAwesome iconFontWithSize:20]
} forState:UIControlStateNormal];
[self.barButton setTitle:[FAKFontAwesome cameraIconWithSize:20].attributedString.string];

或者按照FontAwesomeKit文档中的建议将其转换为UIImage

FAKFontAwesome *cameraIcon = [FAKFontAwesome cameraIconWithSize:20];
UIImage *cameraImage = [cogIcon imageWithSize:CGSizeMake(20, 20)];
[self.barButton setImage:camera];

0

如果您想使用更简单的解决方案而不使用属性文本,请查看我的库。Cocoa Pods也受支持。Font Awesome Swift


0
在Swift 4中,这对我起作用了。
let button1 = UIBarButtonItem(title: "\u{f05a}", style: .plain, target: self, action: #selector(showCartInfoPopUp(_:)))
           
button1.setTitleTextAttributes([.font : UIFont(name: "Font Awesome 5 Pro", size: 24), .foregroundColor : UIColor.white], for: .normal)
            
self.navigationItem.rightBarButtonItem  = button1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接