LoginSignup
7
2

More than 3 years have passed since last update.

[macOS][Cocoa]モーダルシートの表示

Last updated at Posted at 2020-01-30

MacOSでモーダルシートの表示方法

画面

panel.gif

ソース

ViewController

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func openClick(_ sender: Any) {
        let sheetViewController = self.storyboard!.instantiateController(withIdentifier: "SheetViewController") as! SheetViewController
        self.presentAsSheet(sheetViewController)
    }

}

SheetViewController

import Cocoa

class SheetViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 表示されたシートのサイズを固定にする場合
        // self.preferredContentSize = NSSize(width: 300, height: 400)
    }

    deinit {
        print("deinit")
    }

    @IBAction func closeClick(_ sender: Any) {
        self.presentingViewController?.dismiss(self)

        // こっちだと何故か deinit されず。。。
        // 呼び出し元のViewControllerでdismissしないと駄目ってことかな。。。
        // self.dismiss(self)

        // これはOK。理由は後で調べようかな。。。
        // self.dismiss(nil)
    }

}

deinit について補足

モーダルウィンドウを非表示にするには、self(表示側のビューコントローラー)でdismissViewController(_ :)メソッドを呼び出さないといけないようです。
nilにするとOKなのは不明だけど、その場合は恐らくiOSと同じで、VCを指定していないから表示側の親ビューコントローラに処理を移譲していると思われるかな。

To dismiss the sheet, call the dismiss(_:) method on self (the presenting view controller).

The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.

iOSの方の説明なのでmacOSの場合はそうなのかは不明ですが、
公式ドキュメントには原則として呼び出した ViewControlelr が消すべきと書いてあるので
デリゲートかクロージャを使ってdismissを呼び出し元で実行するほうがいいかも。
https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/PresentingaViewController.html

7
2
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
7
2