fc2ブログ

記事一覧

iOS13 でタイトルバーのフォントを変更する方法 | Xamarin.Forms


今回は iOS13 でナビゲーションのタイトルバーのスタイルの適用方法が変更になったことによる影響で iOS12 以前まで正しく動作していたフォントが適用されなくなりました。
そこで iOS13 に対応するべく、ソースコードの変更が迫られましたので、ここにその変更になったソースを覚え書きします。尚、今回のソースコードの他にも前回の記事「タイトルバーのスタイルを変更する方法」にてご紹介しております内容が必要ですので、併せてご確認ください。


iOS13
xamarin_ios_13_title_bar_font_01.png



前提条件
・Windows10 Pro 64Bit 1903
・Visual Studio 2019 Community v16.6.2
・Xamarin 16.6.000.1061 (NuGet Xamarin.Forms 4.6.0.1141)
・macOS Catalina 10.15.3 / Xcode 11.5 / Xamarin.iOS 13.18.2.1



1.事前準備

以前の記事「カスタムフォントを使用してアプリのラベルやボタンに表示させる方法」でもご紹介していますが、以下の項目については設定を済ませておくことが前提です。
・必要なフォントのダウンロード
・各プロジェクトへの配置
・Info.plist の設定
・PostScript名の取得



2.iOS13の場合

2通りの方法があります。
(1)CustomRendererを作成し、描画時に変更するコードを埋め込む
(2)AppDelegateで初回ロード時に読み込む
アプリの仕様によりどちらかまたはその両方を実装する必要があるようです。
さらには
(3)戻る(Back)ボタンに正しいフォントが適用されない場合は、CustomPageRenderer を実装し、フォント変更する必要があります。


CustomNavigationRenderer.csで描画する場合
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationRenderer))]
public class CustomNavigationRenderer : NavigationRenderer
{
private const string fontName = "フォントのPostScript名";

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        //ナビゲーションバーのスタイルを適用する
//iOS13以降はAppDelegateでも実施
CustomNavigationRenderer.SetNavigationStyle(this);
    }

/// <summary>
/// ナビゲーションバーのスタイルを適用する
/// </summary>
/// <param name="instance">NavigationRendererのインスタンス</param>
public static void SetNavigationStyle(IVisualElementRenderer instance)
{
//ナビゲーションのスタイル変更
UINavigationBar.Appearance.BarTintColor = UIColor.White;
UINavigationBar.Appearance.TintColor = UIColor.White;
UINavigationBar.Appearance.BackgroundColor = UIColor.Blue;

//タイトル用のフォント
var titleAttr = new UIStringAttributes()
{
Font = UIFont.FromName(fontName, 20),
ForegroundColor = UIColor.White,
BackgroundColor = UIColor.Blue
};
UINavigationBar.Appearance.TitleTextAttributes = titleAttr;

if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
{
//ナビゲーションバーボタン用のフォント
var buttonAttr = new UIStringAttributes()
{
Font = UIFont.FromName(fontName, 16),
ForegroundColor = UIColor.White,
BackgroundColor = UIColor.Blue
};

var appr = new UINavigationBarAppearance();
appr.ConfigureWithTransparentBackground();
appr.TitleTextAttributes = titleAttr;

var dic = new NSDictionary<NSString, NSObject>(
buttonAttr.Dictionary.Keys.Select(r => r as NSString).ToArray(),
buttonAttr.Dictionary.Values
);

var button = new UIBarButtonItemAppearance(UIBarButtonItemStyle.Plain);
button.Normal.TitleTextAttributes = dic;
button.Highlighted.TitleTextAttributes = dic;
appr.ButtonAppearance = button;
appr.BackButtonAppearance = button;

var done = new UIBarButtonItemAppearance(UIBarButtonItemStyle.Done);
done.Normal.TitleTextAttributes = dic;
done.Highlighted.TitleTextAttributes = dic;
appr.DoneButtonAppearance = done;

UINavigationBar.Appearance.StandardAppearance = appr;
UINavigationBar.Appearance.ScrollEdgeAppearance = appr;
UINavigationBar.Appearance.CompactAppearance = appr;

if (instance != null)
{
//戻るボタンがフォント変更されない場合
var bar = instance.NativeView?.Subviews?.Where(r => r.GetType().BaseType == typeof(UIKit.UINavigationBar)).FirstOrDefault();
if (bar != null)
{
((UIKit.UINavigationBar)bar).StandardAppearance = appr;
}
}
}
}
}

AppDelegate.csで設定する場合
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        //ナビゲーションタイトルの色変更
        //NavigationRendererに実装している機能を呼び出す
CustomNavigationRenderer.SetNavigationStyle(null);

        return base.FinishedLaunching(app, options);
    }
}

CustomPageRenderer.csでの設定も必要です。
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(Page), typeof(CustomPageRenderer))]
public class CustomPageRenderer : PageRenderer
{
private const string fontName = "フォントのPostScript名";

    public override void ViewWillAppear(bool animated)
{
if (this.NavigationController == null ||
this.NavigationController.TopViewController == null)
{
return;
}

UINavigationItem navigationItem = this.NavigationController.TopViewController.NavigationItem;
if (navigationItem != null)
{
//戻るボタンもフォント変更する場合
navigationItem.BackBarButtonItem.SetTitleTextAttributes(new UITextAttributes()
{
Font = UIFont.FromName(fontName, 16),
//イメージピッカーのキャンセルボタンまで白文字になって見えないので、TextColorは指定しない
//TextColor = UIColor.White,
}, UIControlState.Normal);
}
}
}



3.関連記事

ラベルやボタンにカスタムフォントを適用させる方法については以下の記事にて紹介しております。
https://itblog.dynaspo.com/blog-entry-156.html

タイトルバーのスタイルを変更する方法(iOS12以前とAndroid)については以下の記事にて紹介しております。
https://itblog.dynaspo.com/blog-entry-157.html

ListView の ImageCell にカスタムフォントを適用させる方法については以下の記事にて紹介しております。
https://itblog.dynaspo.com/blog-entry-387html








最後までお読みいただきありがとうございます。
当ブログの内容をまとめた Xamarin逆引きメニュー は以下のURLからご覧になれます。
https://itblog.dynaspo.com/blog-entry-81.html



関連記事

コメント

コメントの投稿

※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。

 入力されていないコメントには返信しませんのであらかじめご了承くださいませ。

※ニックネームでも良いので必ずご入力ください。

    

※必ずご入力ください。

    
    

※必ずご入力ください。

※技術的な質問には環境やエラーについて正確かつ詳細にお教えください。

・正確なエラーの内容

・Windowsのバージョン番号

・Visual Studioのバージョン

・機器の型番

・アプリやソフトのバージョン

    

カテゴリ別記事一覧

広告

プロフィール

石河 純


著者名 :石河 純
自己紹介:素人上がりのIT技術者。趣味は卓球・車・ボウリング

IT関連の知識はざっくりとこんな感じです。
【OS関連】
WindowsServer: 2012/2008R2/2003/2000/NT4
Windows: 10/8/7/XP/2000/me/NT4/98
Linux: CentOS RedHatLinux9
Mac: macOS Catalina 10.15 / Mojave 10.14 / High Sierra 10.13 / Sierra 10.12 / OSX Lion 10.7.5 / OSX Snow Leopard 10.6.8
【言語】
VB.net ASP.NET C#.net Java VBA
Xamarin.Forms
【データベース】
Oracle 10g/9i
SQLServer 2016/2008R2/2005/2000
SQLAnywhere 16/11/8
【BI/レポートツール】
Cognos ReportNet (IBM)
Microsoft PowerBI
ActiveReport (GrapeCity)
CrystalReport
【OCX関連】
GrapeCity InputMan SPREAD MultiRow GridView
【ネットワーク関連】
CCNP シスコ技術者認定
Cisco Catalyst シリーズ
Yamaha RTXシリーズ
FireWall関連
【WEB関連】
SEO SEM CSS jQuery IIS6/7 apache2

休みの日は卓球をやっています。
現在、卓球用品通販ショップは休業中です。