Swift iPad iPhone(別StoryBoard)実装方法

ストーリーボードは当然、iphone,ipad2つ用意する必要があります。
問題は、ソース。
同じ処理を書くことが多い。
それで、同じファイルに記述する方法を記載します。

まずファイル名。これは何でも良いが理解しやすい名前が良い。関係する名前がいいと思います。
この場合は

MsPersonData.swift

でファイル名を作成。

iPhone,iPadともにMsPersonDataUniを継承する。 MsPersonDataUniに共通処理を記載。

import UIKit
import MapKit
import CoreData
/// 訪問先(iPad用ペイン)
class MsPersonDataPad: MsPersonDataUni {

@IBAction ~

ここで画面接続もする。 その際ストーリーボードはそれぞれiPhone,iPad違うファイルに接続可能。

iPhone画面 MsPersonDataUniを継承する。

/// 訪問先(iPhone用画面)
class MsPersonDataPhn: MsPersonDataUni {
    //..........................................................................
    //MARK: Outlets & Properties
    @IBOutlet weak var mkMap: MKMapView!

基本的に、画面接続のところが大多数を占めると思われる。 共通の処理はここに記載

ここでは画面接続もiPhone,iPadともに接続可能。

はじめは驚くかもしれない. 同じuiMailを接続している。

MsPersonDataUniはここで初めてUIViewControllerを継承している。

/// 訪問先本体(iPad & iPhone 共通)
class MsPersonDataUni: UIViewController, MsMapAgentDelegate {
  @IBOutlet weak var uiMail: UITextField!

こちらはiPad

f:id:happy_teeth_ago:20180828135722p:plain:w500

こちらはiPhone

f:id:happy_teeth_ago:20180828135802p:plain:w500

それぞれ接続できている。

これはstoyBoardでそれぞれiPhone,iPadのクラスを指定している為

注意!segueでのprepar for segue はそれぞれiPhone,iPadのクラスに記載する必要があります。

次にAppDelegateの実装

//自作の関数
   func storyboardName()->String{
        if ((UIDevice.current).userInterfaceIdiom) == UIUserInterfaceIdiom.phone {
            //iPhoneのストーリーボードを返す
            return "iPhone"
        }else{
            return "Main"
        }
    }

上記を呼ぶのがここ

//デリゲートメソッド
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
   
        //画面の向きの設定 上記関数を呼んでいる
        let storyboard: UIStoryboard = UIStoryboard(name: storyboardName(), bundle: nil)
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        
        self.window?.rootViewController = storyboard.instantiateInitialViewController()
        //表示の更新 uiwindowは更新しないといけない
        self.window?.makeKeyAndVisible()

        let path = NSSearchPathForDirectoriesInDomains(
            .applicationSupportDirectory, .userDomainMask,true).first!
        
        return true
    }


    //初回起動時の画面の向き
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        
        if ((UIDevice.current).userInterfaceIdiom) == UIUserInterfaceIdiom.phone {
            //iPhoneのストーリーボードを返す
            return [.portrait , .portraitUpsideDown]
        }else{
            //ipadのストーリーボードを返す
//.landscapeでアクセスできるのは、readonlyのプロパティーだから
            return .landscape
        }
        
    }

デバイスの回転や、画面の向きの制御を行う UIInterfaceOrientationMask 定義

構造体で取得のみです。だから .portrait でアクセスできます。

public struct UIInterfaceOrientationMask : OptionSet {

    public static var portrait: UIInterfaceOrientationMask { get }

    public static var landscapeLeft: UIInterfaceOrientationMask { get }