【技術ソリューション事例#1】[.NET MAUI]EntryをAndroidとiOSで同じ見た目にする

| 0

はじめに

.NET MAUIのコンポーネントの中には、Entry(AndroidでいうEditText, iOSではTextField)などAndroidとiOSでデフォルトの見た目が違うものがあります。デザインの要望で両OSの見た目を揃えたい場合があると思いますが、XAMLだけで対応できない部分は、設定が少し複雑になります。

以下の公式ドキュメントを参考に、具体的な手順をご紹介します。

概要を説明すると、XAMLなどで記述できる.NET MAUIの各Viewクラスとネイティブアプリの各Viewクラスの間に、HandlerクラスというOS別にネイティブアプリのViewクラスのラッパークラスが存在します。そのHandlerを使うことで、.NET MAUIアプリからネイティブアプリと同じように、Viewのカスタマイズを行うことができます。

Android:Entryの下線を非表示にする

EntryHandlerを用いて、AndroidのEditTextに命令する方法で対応します。そのために、まずAndroidのEditTextの下線を消す方法を調べます。

“EditText 下線 消す”などで調べると、android:backgroundをnullにする、#00000000(透明)を入れるなど出てきます。

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:hint="ログイン" />

実際に.NET MAUIのコードに適用します。
今回はAndroidアプリ全体に適用するため、Platforms/Android/MainApplication.csに記述します。これはネイティブアプリのapplicationクラスに対応しています。
AppendToMapping内でandroid:backgroundをnullに対応するhandler.PlatformView.Background = null;を記載します。

using Android.App;
using Android.Runtime;

namespace CustomEntryApp
{
    [Application]
    public class MainApplication : MauiApplication
    {
        public MainApplication(IntPtr handle, JniHandleOwnership ownership)
            : base(handle, ownership)
        {
            Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
            {
                handler.PlatformView.Background = null;
            });
        }

        protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
    }
}

iOS: Entryの周りの枠を非表示にする

次は、iOSのTextFiledの枠を非表示にする方法を調べます。
公式ドキュメントによると、TextFiledのUITextBorderStyleで枠の表示を変えられるようです。

iOS側も.NET MAUIのコードに適用します。
Androidと同様に、iOSアプリ全体に適用するため、Platforms/iOS/AppDelegate.csに記述します。これもswiftのAppDelegateに対応します。

using Foundation;
using Microsoft.Maui.Handlers;
using UIKit;

namespace CustomEntryApp
{
    [Register("AppDelegate")]
    public class AppDelegate : MauiUIApplicationDelegate
    {
        protected override MauiApp CreateMauiApp()
        {
            EntryHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
            {
                handler.PlatformView.BorderStyle = UITextBorderStyle.None;
            });

            return MauiProgram.CreateMauiApp();
        }
    }
}

これで、AndroidとiOSの両方共、枠と下線が無いEntryが出来ました。後は、Entryとは別にXAML上でレイアウトを装飾するなどして、カスタマイズしていきます。