LoginSignup
5
5

More than 3 years have passed since last update.

[Swift] PanModalでお手軽にモーダルを実装する

Last updated at Posted at 2020-12-27

アプリを作るときに、モーダルシートを使うことは結構ありますよね。
そこで、簡単に実装できるようにライブラリを使っていきたいと思います。
今回はPanModalを使って実装していきます。

詳しく見たい方はこちらどうぞ↓
PanModal

ライブラリの導入

Podfileを作成して、以下の記述を行います

pod 'PanModal'

表示するものを作る

まずは、PanModalをインポートしましょう

import UIKit
import PanModal

モーダルに表示させるクラスはPanModalPresentableが適用されていなければいけません。
今回モーダルに表示するクラスをModalViewControllerとします。

ModalViewController.swift
class ModalViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBlue
    }
}
ModalViewController.swift
extension ModalViewController: PanModalPresentable {
    var panScrollable: UIScrollView? {
        return nil
    }
    // モーダルの高さを画面下端から200にする(モーダルを表示した時のデフォルトの高さ)
    var shortFormHeight: PanModalHeight {
        return .contentHeight(200)
    }
    // モーダルの高さを画面上端から最大400に制限する
    // この値を設定しないとモーダルが画面の一番上までスワイプできてしまう
    var longFormHeight: PanModalHeight {
        return .maxHeightWithTopInset(400)
    }
    // モーダルの背景色
    var panModalBackgroundColor: UIColor {
        return UIColor.black.withAlphaComponent(0.2)
    }
    // 上にスワイプできるかどうか(デフォルトではtrue)
    var anchorModalToLongForm: Bool {
        return false
    }
    // モーダル上端の角に丸みをつけるかどうか
    var shouldRoundTopCorners: Bool {
        return true
    }
    // ホームボタンがないスマホのホームバーみたいなやつを表示するかどうか
    var showDragIndicator: Bool {
        return true
    }
    // 表示したモーダルをユーザーが操作できるかどうか(falseにすると操作できなくなる)
    var isUserInteractionEnabled: Bool {
        return false
    }
}

表示させるものを作る

ViewController.swift
class ViewController: UIViewController {

    let button: UIButton = {
        let button = UIButton()
        button.setTitle("表示!", for: .normal)
        button.titleLabel?.font = .boldSystemFont(ofSize: 20)
        button.layer.cornerRadius = 20
        button.backgroundColor = .orange
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        button.center = view.center
        button.addTarget(self, action: #selector(presentModal(_:)), for: .touchUpInside)
        view.addSubview(button)
    }

    @objc func presentModal(_ sender: UIButton) {
        presentPanModal(ModalViewController())
    }
}

モーダルを表示するときはpresentPanModalに、モーダル用に作ったModalViewControllerを入れて呼び出してあげなければいけません。
この例で言うとボタンにモーダルを表示する処理を加えてpresentPanModalを呼び出しています。

表示結果

最後に

Panといえばあるピアニストが思い浮かぶ私ですが、まあまあわかりやすく書けたかなと思います。
ライブラリは便利なのでみんな使っていこう!と言うことで、読んでくださりありがとうがございました。

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