iOS:在UIBarButtonItem和Button中添加带有标题的FontAwesome图标

时间:2015-12-26 05:53:11

标签: ios objective-c uibutton uibarbuttonitem font-awesome

我想在我的NavigationBar和

中使用这样的UIBarButton项目

enter image description here

像这样的普通UIButton

enter image description here

我已经尝试过使用这些链接了 Question 1 Question 2 Question 3但未获得输出。

我需要将FontAwesome图标附加到按钮标题文本。

有人可以提供帮助吗?

我的代码是:

NSString *icon = [NSString fontAwesomeIconStringForIconIdentifier:@"fa-folder-open"];

NSString *locationString = [NSString stringWithFormat:@"%@ %@", icon, @"Change"];

NSMutableAttributedString *astring = [[NSMutableAttributedString alloc] initWithString:locationString];

[astring addAttribute:NSFontAttributeName
                value:[UIFont iconicFontOfSize:20]
                range:NSMakeRange(0,1)]; // The first character

changeFolderButton.titleLabel.attributedText = astring;

3 个答案:

答案 0 :(得分:4)

如果FontAwesome图标的代码为"&#xf007",则将文字设置为@"\U0000f007"为标题。

使用以下代码 UIButton : -

myBtn.titleLabel.font =[UIFont fontWithName:@"FontAwesome" size:20.0];
[myBtn setTitle:@"\U0000f007" forState:UIControlStateNormal]];

使用以下代码 UIBarButton : -

[self.barButton setTitleTextAttributes:@{
              NSFontAttributeName: [UIFont fontWithName:@"FontAwesome" size:24.0],
              NSForegroundColorAttributeName: self.view.tintColor
                                     } forState:UIControlStateNormal]; 
[self.barButton setTitle:@"\U0000f007"]];

如果要附加带有图标的字符串,请使用以下代码: -

NSString * myString = @"\U0000f007 Change";
NSMutableAttributedString *astring = [[NSMutableAttributedString alloc] initWithString:myString];
[astring addAttribute:NSFontAttributeName
                value:[UIFont fontWithName:@"FontAwesome" size:22.0]
                range:NSMakeRange(0,1)]; //If Icon is on starting position
[myBtn setAttributedTitle:astring forState:UIControlStateNormal];

希望,这就是你要找的东西。任何关注都会回复给我。 :)

答案 1 :(得分:1)

在swift 2.0中:

    btnAddGroup.titleLabel?.font = UIFont(name:"FontAwesome",size: 50)
    btnAddGroup.setTitle(String.fontAwesomeIconWithCode("fa-plane"), forState: .Normal)

答案 2 :(得分:-1)

对于迟到的回答感到抱歉,但这可能会对将来有所帮助,注意:Facebook表示我的UIButton

FAKFontAwesome *Gplus = [FAKFontAwesome googleIconWithSize:20];
    [Gplus addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor]];
    NSMutableAttributedString *twitterMass = [[Gplus attributedString] mutableCopy];
    [twitterMass appendAttributedString:[[NSAttributedString alloc] initWithString:@" Login With Google" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}]];
    [Facebook setAttributedTitle:twitterMass forState:UIControlStateNormal];