27
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIBarButtonItemにアイコンフォント(FontAwesome)を設定する。

Last updated at Posted at 2014-07-02

navbarbutton-with-fontawesome2.png

左上Githubアイコンを指定する方法です。これはフォントであり画像ではありません。
コードで自由に色やサイズを変更できます。

Cocoapodsでのインストール

platform :ios, '7.0'
pod 'BlocksKit', '~> 2.2'
pod 'FontAwesome+iOS', :git => 'https://github.com/alexdrone/ios-fontawesome'

フォントは以下の場所に入ります。
Pods > FontAwesome+iOS > Resources > FontAwesome.ttf
YourProjectName-Info.plistにFonts provided by applicationを追加し、その中のitem 0, item 1などのValueにFontAwesome.ttfと書くとフォントが使えるようになります。

ライブラリの読み込み

#import <BlocksKit+UIKit.h>
#import <FontAwesome+iOS/NSString+FontAwesome.h>
#import <FontAwesome+iOS/UIFont+FontAwesome.h>

UIBarButtonItemを指定

UIBarButtonItem *cancelItem =
    [[UIBarButtonItem alloc]
            bk_initWithTitle:[NSString fontAwesomeIconStringForEnum:FAGithub]
                       style:UIBarButtonItemStylePlain
                     handler:^(id sender) {
            // do something
        }];
[cancelItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:kFontAwesomeFamilyName size:30.0],
            NSForegroundColorAttributeName:[UIColor colorWithRed:0.411 green:0.057 blue:0.058 alpha:1.000]
            } forState:UIControlStateNormal];
self.navigationItem.leftBarButtonItem = cancelItem;

このコードでは別のライブラリのBlocksKitと一緒に使っていますが、アイコンを表示するという目的には必須ではありません。

追記: 別法

UIButton *iconButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[iconButton bk_addEventHandler:^(id sender) {

        NSLog(@"Tapped!");

        [sender setTitleColor:[UIColor colorWithRed:0.411 green:0.057 blue:0.058 alpha:1.000] forState:UIControlStateNormal];
    } forControlEvents:UIControlEventTouchUpInside];
[iconButton setTitle:[NSString fontAwesomeIconStringForEnum:FAGithub] forState:UIControlStateNormal];
iconButton.titleLabel.font = [UIFont fontWithName:kFontAwesomeFamilyName size:36.0];
iconButton.titleLabel.textColor = [UIColor colorWithRed:0.411 green:0.057 blue:0.058 alpha:1.000];

UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] init];
[cancelItem setCustomView:iconButton];
self.navigationItem.leftBarButtonItem = cancelItem;

こちらの方は位置を調整できるので良いかもしれません。タップしたあとに色が白くなってしまうのを防止するために再度色を設定するようにしています。

参照

http://fortawesome.github.io/Font-Awesome/
https://github.com/alexdrone/ios-fontawesome

27
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?