Hello, iOS – クイックスタート

警告

iOS Designer は、Visual Studio 2019 バージョン 16.8 および Visual Studio 2019 for Mac バージョン 8.8 で非推奨とされ、Visual Studio 2019 バージョン 16.9 および Visual Studio for Mac バージョン 8.9 から削除されています。 iOS のユーザー インターフェイスについては、Xcode の Interface Builder が実行されている Mac で直接ビルドすることをお勧めします。 詳細については、「Xcode を使用したユーザーインターフェイスの設計」を参照してください。

このガイドでは、ユーザーが入力した英字の電話番号を数値の電話番号に変換してから、その番号に電話をかけるアプリケーションの作成方法を説明します。 最終的にアプリケーションは次のようになります。

The Hello.iOS Quickstart app

要件

Xamarin を使用した iOS 開発の要件:

  • macOS High Sierra (10.13) 以降を実行している Mac。
  • App Store からインストールした最新版の Xcode と iOS SDK。

Xamarin.iOS は次のセットアップで機能します。

  • 上記の仕様を満たす最新版の Visual Studio for Mac。

Xamarin.iOS Mac インストール ガイドで段階的インストール手順をご確認いただけます

Xamarin.iOS は次のセットアップで機能します。

  • 最新版の Visual Studio 2019 または Visual Studio 2017 Community、Professional、または Enterprise。Windows 10。上記の仕様を満たす Mac ビルド ホストとペア。

Xamarin.iOS Windows インストール ガイドでステップ バイ ステップのインストール手順をご確認いただけます。

始める前に、Xamarin アプリ アイコン セットをダウンロードしてください。

Visual Studio for Mac のチュートリアル

このチュートリアルでは、英数字の電話番号を数字の電話番号に変換する Phoneword という名称のアプリケーションを作成する方法を説明します。

  1. Applications フォルダーまたはスポットライトから Visual Studio for Mac を起動します。

    The Launch screen

    起動画面で、[新しいプロジェクト...] をクリックして、新しい Xamarin.iOS ソリューションを作成します。

    iOS solution

  2. [新しいソリューション] ダイアログで、iOS > アプリ>のシングル ビュー アプリケーション テンプレートを選択し、C# が選択されていることを確認します。 [次へ] をクリックします。

    Choose Single View Application

  3. アプリを構成します。 [名前]Phoneword_iOS を指定し、他のすべてを既定値のままにします。 [次へ] をクリックします。

    Enter the app name

  4. プロジェクトとソリューションの名前はそのままにします。 ここでプロジェクトの場所を選択するか、既定のままにします。

    Choose the location of the project

  5. [作成] をクリックしてソリューションを作成します。

  6. Solution PadMain.storyboard ファイルをダブルクリックして開きます。 Visual Studio iOS デザイナーを使用してファイルを開きます (ストーリーボードを右クリックし、[iOS デザイナーで>開く] を選択します)。 これで目視で確認しながら UI を作成できます。

    The iOS Designer

    "サイズ クラス" は既定で有効になっています。 詳細については、Unified Storyboards ガイドをご覧ください。

  7. ツールボックス パッドの検索バーに「label」と入力し、デザイン サーフェイス (中央の領域) にラベルをドラッグします。

    Drag a Label onto the design surface the area in the center

    Note

    [プロパティ パッド] または [ツールボックス] は、[パッドの表示] に移動することでいつでも表示>できます。

  8. ドラッグ コントロールのハンドル (コントロールを囲む円) をつかみ、ラベルを大きくします。

    Make the label wider

  9. デザイン サーフェイスでラベルが選択されている状態で、[プロパティ] パッドを利用し、[ラベル][テキスト] プロパティを "Enter a Phoneword:" に変更します。

    Set the label to Enter a Phoneword

  10. ツールボックス内で “テキスト フィールド” を検索し、[ツールボックス][テキスト フィールド] をデザイン サーフェイスにドラッグし、[ラベル] の下に置きます。 テキスト フィールドの幅がラベルの幅と同じになるまで幅を調整します。

    Make the Text Field the same width as the Label

  11. デザイン サーフェイスでテキスト フィールドが選択されている状態で、Properties Pad の ID セクションの [テキスト フィールド][名前] プロパティを PhoneNumberText に変更し、[テキスト] プロパティを "1-855-XAMARIN" に変更します。

    Change the Title property to 1-855-XAMARIN

  12. [ボタン][ツールボックス] からデザイン サーフェスにドラッグし、[テキスト フィールド] の下に配置します。 ボタンの幅がテキスト フィールドラベルの幅と同じになるように幅を調整します。

    Adjust the width so the Button is as wide as the Text Field and Label

  13. デザイン サーフェイスでボタンが選択されている状態で、Properties Pad[ID] セクションの [名前] プロパティを TranslateButton に変更します。 [タイトル] プロパティを "Translate" に変更します。

    Change the Title property to Translate

  14. 上記の 2 つの手順を繰り返し、[ボタン][ツールボックス] からデザイン サーフェスにドラッグし、最初の [ボタン] の下に配置します。 ボタンの幅が最初のボタンの幅と同じになるように幅を調整します。

    Adjust the width so the Button is as wide as the first Button

  15. デザイン サーフェイスで 2 つ目のボタンが選択されている状態で、[プロパティ] パッドの [ID] セクションの [名前] プロパティを CallButton に変更します。 [タイトル] プロパティを "Call" に変更します。

    Change the Title property to Call

    [ファイルの保存] に移動するか、⌘+ s キーを押して変更を保存します。>

  16. 電話番号を英数字から数字に変換するには、いくつかのロジックをアプリに追加する必要があります。 ソリューション パッドで 電話word_iOSプロジェクトを右クリックし、[新しいファイルの追加] を選択するか、⌘+ n キーをして、新しいファイルをプロジェクトに追加>します。

    Add a new file to the Project

  17. [新しいファイル] ダイアログで、[全般>空のクラス] を選択し、新しいファイルに名前を付けますPhoneTranslator

    Select Empty Class and name the new file PhoneTranslator

  18. これで、新しい空の C# クラスが作成されます。 テンプレート コードをすべて削除し、次のコードに置き換えます。

    using System.Text;
    using System;
    
    namespace Phoneword_iOS
    {
        public static class PhoneTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw)) {
                    return "";
                } else {
                    raw = raw.ToUpperInvariant();
                }
    
                var newNumber = new StringBuilder();
                foreach (var c in raw)
                {
                    if (" -0123456789".Contains(c)) {
                        newNumber.Append(c);
                    } else {
                        var result = TranslateToNumber(c);
                        if (result != null) {
                            newNumber.Append(result);
                        }
                    }
                    // otherwise we've skipped a non-numeric char
                }
                return newNumber.ToString();
            }
    
            static bool Contains (this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
    
            static int? TranslateToNumber(char c)
            {
                if ("ABC".Contains(c)) {
                    return 2;
                } else if ("DEF".Contains(c)) {
                    return 3;
                } else if ("GHI".Contains(c)) {
                    return 4;
                } else if ("JKL".Contains(c)) {
                    return 5;
                } else if ("MNO".Contains(c)) {
                    return 6;
                } else if ("PQRS".Contains(c)) {
                    return 7;
                } else if ("TUV".Contains(c)) {
                    return 8;
                } else if ("WXYZ".Contains(c)) {
                    return 9;
                }
                return null;
            }
        }
    }
    

    PhoneTranslator.cs ファイルを保存して閉じます。

  19. ユーザー インターフェイスを接続するコードを追加します。 Solution PadViewController.cs をダブルクリックして開きます。

    Add code to wire up the user interface

  20. 最初に TranslateButton を接続します。 ViewController クラスで、ViewDidLoad メソッドを見つけ、base.ViewDidLoad() 呼び出しの下に次のコードを追加します。

    string translatedNumber = "";
    
    TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
        // Convert the phone number with text to a number
        // using PhoneTranslator.cs
        translatedNumber = PhoneTranslator.ToNumber(
            PhoneNumberText.Text);
    
        // Dismiss the keyboard if text field was tapped
        PhoneNumberText.ResignFirstResponder ();
    
        if (translatedNumber == "") {
            CallButton.SetTitle ("Call ", UIControlState.Normal);
            CallButton.Enabled = false;
        } else {
            CallButton.SetTitle ("Call " + translatedNumber,
                UIControlState.Normal);
            CallButton.Enabled = true;
        }
    };
    

    ファイルの名前空間が異なる場合、using Phoneword_iOS; を追加します。

  21. 2 つ目のボタンである CallButton をユーザーが押したときに応答するためのコードを追加します。 TranslateButton のコードの下に次のコードを配置し、ファイルの一番上に using Foundation; を追加します。

        CallButton.TouchUpInside += (object sender, EventArgs e) => {
            // Use URL handler with tel: prefix to invoke Apple's Phone app...
            var url = new NSUrl ("tel:" + translatedNumber);
    
            // ...otherwise show an alert dialog
            if (!UIApplication.SharedApplication.OpenUrl (url)) {
                var alert = UIAlertController.Create ("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
                alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null));
                PresentViewController (alert, true, null);
            }
        };
    
  22. 変更を保存し、[Build All]\(すべてビルド\) を選択するか、⌘+ B キーをしてアプリケーションをビルド>します。アプリケーションがコンパイルされると、IDE の上部に成功メッセージが表示されます。

    A success message will appear at the top of the IDE

    エラーがある場合は、アプリケーションが正常にビルドされるまで、前の手順を実行し、誤りを修正します。

  23. 最後に iOS シミュレーターでアプリケーションをテストします。 IDE の左上で、最初のドロップダウンから [デバッグ] を選択し、2 つ目のドロップダウンから [iPhone XR iOS 12.0] (またはその他の使用可能なシミュレーター) を選択し、[開始] (再生ボタンに似た三角形のボタン) を押します。

    Select a simulator and press start

    Note

    現在のところ、Apple の要件に起因し、場合によっては、デバイスまたはシミュレーターのコードをビルドするため、開発証明書または "署名 ID" を用意する必要があります。 デバイス プロビジョニング ガイドの手順に従ってこれを設定します。

  24. これにより、iOS シミュレーター内でアプリケーションが起動します。

    The application running inside the iOS Simulator

    iOS シミュレーターでは通話に対応していません。代わりに、電話をかけようとすると警告ダイアログが表示されます。

    The alert dialog when trying to place a call

Visual Studio チュートリアル

このチュートリアルでは、英数字の電話番号を数字の電話番号に変換する Phoneword という名称のアプリケーションを作成する方法を説明します。

Note

このチュートリアルでは、Windows 10 仮想マシンの Visual Studio Enterprise 2017 を使用します。 上記の要件を満たす限り、実際のセットアップはこれと異なってもかまいません。一部のスクリーンショットが実際とは異なる場合があります。

Note

このチュートリアルを進める前に、Visual Studio から Mac に接続しておく必要があります。 これは、Xamarin.iOS が、アプリケーションのビルドと起動に Apple のツールを利用するからというのが理由です。 「Mac とペアリング」ガイドの手順に従い、設定を始めます。

  1. [スタート] メニューから Visual Studio を起動します。

    The Start screen

    [新しいプロジェクトのファイル>]を選択して、新しい > Xamarin.iOS ソリューションを作成します。.. >Visual C# > i電話 & iPad > iOS アプリ (Xamarin):

    Select iOS App (Xamarin) project type

    次に表示されたダイアログで [単一ビュー アプリ] テンプレートを選択し、[OK] をクリックしてプロジェクトを作成します。

    Select Single View project template

  2. ツール バーの [Xamarin Mac エージェント] アイコンが緑であることを確認します。

    Confirm that the Xamarin Mac Agent icon in the toolbar is green

    緑でない場合は、Mac ビルド ホストへの接続がないことを示しているため、構成ガイドの手順に従って接続します。

  3. ソリューション エクスプローラー で iOS デザイナーの Main.storyboard ファイルをダブルクリックして開きます。

    The iOS Designer

  4. [ツールボックス] タブの検索バーに「label」と入力し、デザイン サーフェイス (中央の領域) にラベルをドラッグします。

    Drag a Label onto the design surface the area in the center

  5. 次に、ドラッグ コントロールのハンドルをつかみ、ラベルを大きくします。

    Make the label wider

  6. デザイン サーフェイスでラベルが選択されている状態で、[プロパティ] ウィンドウを利用し、[ラベル][テキスト] プロパティを "Enter a Phoneword:" に変更します。

    Change the Text property of the Label to Enter a Phoneword

    Note

    [表示] メニューに移動すれば、[プロパティ][ツールボックス] をいつでも表示できます。

  7. ツールボックス内で “テキスト フィールド” を検索し、[ツールボックス][テキスト フィールド] をデザイン サーフェイスにドラッグし、[ラベル] の下に置きます。 テキスト フィールドの幅がラベルの幅と同じになるまで幅を調整します。

    Adjust the width until the Text Field is the same width as the Label

  8. デザイン サーフェイスでテキスト フィールドが選択されている状態で、[プロパティ] パッドの ID セクションの [テキスト フィールド][名前] プロパティを PhoneNumberText に変更し、[テキスト] プロパティを "1-855-XAMARIN" に変更します。

    Change the Text property to 1-855-XAMARIN

  9. [ボタン][ツールボックス] からデザイン サーフェスにドラッグし、[テキスト フィールド] の下に配置します。 ボタンの幅がテキスト フィールドラベルの幅と同じになるように幅を調整します。

    Adjust the width so the Button is as wide as the Text Field and Label

  10. デザイン サーフェイスでボタンが選択されている状態で、[プロパティ] パッドの [ID] セクションの [名前] プロパティを TranslateButton に変更します。 [タイトル] プロパティを "Translate" に変更します。

    Change the Title property to Translate

  11. 前の 2 つの手順を繰り返し、[ボタン][ツールボックス] からデザイン サーフェスにドラッグし、最初の [ボタン] の下に配置します。 ボタンの幅が最初のボタンの幅と同じになるように幅を調整します。

    Adjust the width so the Button is as wide as the first Button

  12. デザイン サーフェイスで 2 つ目のボタンが選択されている状態で、[プロパティ][ID] セクションの [名前] プロパティを CallButton に変更します。 [タイトル] プロパティを "Call" に変更します。

    Change the Title property to Call

    [すべて保存] > に移動するか、Ctrl キーを押しながら s キーを押して、変更を保存します

  13. 電話番号を英数字から数字に変換するコードをいくつか追加します。 これを行うには、まず、ソリューション エクスプローラーの 電話word プロジェクトを右クリックし、[新しい項目の追加]を選択して新しいファイルをプロジェクトに追加>します。または、Ctrl + Shift + A キーをします。

    Add some code to translate phone numbers from alphanumeric to numeric

  14. [新しい項目の追加] ダイアログで (プロジェクトを右クリックし、[新しい項目の追加>...] を選択)、Apple > クラスを選択し、新しいファイルPhoneTranslatorに名前を付けます。

    Add a new class named PhoneTranslator

    重要

    アイコンに C# がある 'class' テンプレートを必ず選択してください。 それ以外を選択すると、この新しいクラスを参照できないことがあります。

  15. これで、新しい C# クラスが作成されます。 テンプレート コードをすべて削除し、次のコードに置き換えます。

    using System.Text;
    using System;
    
    namespace Phoneword
    {
        public static class PhoneTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw)) {
                    return "";
                } else {
                    raw = raw.ToUpperInvariant();
                }
    
                var newNumber = new StringBuilder();
                foreach (var c in raw)
                {
                    if (" -0123456789".Contains(c)) {
                        newNumber.Append(c);
                    } else {
                        var result = TranslateToNumber(c);
                        if (result != null) {
                            newNumber.Append(result);
                        }
                    }
                    // otherwise we've skipped a non-numeric char
                }
                return newNumber.ToString();
            }
    
            static bool Contains (this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
    
            static int? TranslateToNumber(char c)
            {
                if ("ABC".Contains(c)) {
                    return 2;
                } else if ("DEF".Contains(c)) {
                    return 3;
                } else if ("GHI".Contains(c)) {
                    return 4;
                } else if ("JKL".Contains(c)) {
                    return 5;
                } else if ("MNO".Contains(c)) {
                    return 6;
                } else if ("PQRS".Contains(c)) {
                    return 7;
                } else if ("TUV".Contains(c)) {
                    return 8;
                } else if ("WXYZ".Contains(c)) {
                    return 9;
                }
                return null;
            }
        }
    }
    

    PhoneTranslator.cs ファイルを保存して閉じます。

  16. ハンドルとボタンの相互作用にロジックを追加できるように、ソリューション エクスプローラーViewController.cs をダブルクリックして開きます。

    Logic added to handle interactions with the buttons

  17. 最初に TranslateButton を接続します。 ViewController クラスで、ViewDidLoad メソッドを見つけます。 ViewDidLoad 内の base.ViewDidLoad() 呼び出しの下に次のボタン コードを追加します。

    string translatedNumber = "";
    
    TranslateButton.TouchUpInside += (object sender, EventArgs e) => {
    
        // Convert the phone number with text to a number
        // using PhoneTranslator.cs
        translatedNumber = PhoneTranslator.ToNumber(PhoneNumberText.Text);
    
        // Dismiss the keyboard if text field was tapped
        PhoneNumberText.ResignFirstResponder ();
    
        if (translatedNumber == "") {
            CallButton.SetTitle ("Call", UIControlState.Normal);
            CallButton.Enabled = false;
            }
        else {
            CallButton.SetTitle ("Call " + translatedNumber, UIControlState.Normal);
            CallButton.Enabled = true;
            }
    };
    

    ファイルの名前空間が異なる場合、using Phoneword; を追加します。

  18. 2 つ目のボタンである CallButton をユーザーが押したときに応答するためのコードを追加します。 TranslateButton のコードの下に次のコードを配置し、ファイルの一番上に using Foundation; を追加します。

    CallButton.TouchUpInside += (object sender, EventArgs e) => {
        var url = new NSUrl ("tel:" + translatedNumber);
    
            // Use URL handler with tel: prefix to invoke Apple's Phone app,
            // otherwise show an alert dialog
    
        if (!UIApplication.SharedApplication.OpenUrl (url)) {
                        var alert = UIAlertController.Create ("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
                        alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null));
                        PresentViewController (alert, true, null);
                    }
    };
    
  19. 変更を保存し、ビルド ソリューションのビルドを選択するか、Ctrl + Shift + B キーをしてアプリケーションをビルド>します。アプリケーションがコンパイルされると、IDE の下部に成功メッセージが表示されます。

    A success message will appear at the bottom of the IDE

    エラーがある場合は、アプリケーションが正常にビルドされるまで、前の手順を実行し、誤りを修正します。

  20. 最後にリモートの iOS シミュレーターでアプリケーションをテストします。 IDE ツール バーで、ドロップダウン メニューから [デバッグ][iPhone 8 Plus iOS x.x] を選択し、[開始] (再生ボタンに似た緑の三角形) を押します。

    Press Start

  21. これにより、iOS シミュレーター内でアプリケーションが起動します。

    The application running inside the iOS Simulator

    iOS シミュレーターでは通話に対応していません。代わりに、電話をかけようとすると警告ダイアログが表示されます。

    An alert dialog will display when trying to place a call

おつかれさまでした。これで最初の Xamarin.iOS アプリケーションが完成しました。

次は、「Hello, iOS Deep Dive」で、このガイドに登場したツールやスキルを詳しく分析します。