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

我想在我的NavigationBar中使用这样的UIBarButton项目

在此处输入图像描述

像这样的普通UIButton

在此处输入图像描述

我已经尝试过使用这些链接问题1 问题2 问题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; 

如果FontAwesome图标的代码是"" ,则将文本设置为@"\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]; 

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

在swift 2.0中:

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

对不起,迟到的答案,但这可能会帮助将来的人,注意: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];