2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】SideMenu ライブラリでメニュー表示時に背景を暗くする

Last updated at Posted at 2020-07-17

SideMenu というライブラリを使用しサイドメニューを実装しました。
サイドメニュー表示時に背景を暗くする方法が分からなかったので、以下の手順で実現します。

  1. 画面全体を覆う半透明の coverView を作成する。
  2. サイドバー表示時に上記の coverView を元の View の前面に表示させる。
  3. サイドバーが閉じた時に coverView を破棄する。

環境

  • Xcode 11.5
  • Swift 5.2.4

今回の例では NavigationController が設定されている前提で書いています。

画面全体を覆う View を作成

ViewController.swift
private let coverView: UIView = {
    let mainBoundSize: CGSize = UIScreen.main.bounds.size
    let mainFrame = CGRect(x: 0, y: 0, width: mainBoundSize.width, height: mainBoundSize.height)

    let view = UIView()
    view.frame = mainFrame
    view.backgroundColor = UIColor(white: 0, alpha: 0.3)
    return view
}()

UIScreen.main.bounds.size で画面サイズを取得し、画面に等しいサイズの View を作成しています。

サイドメニュー表示時に View を表示

SideMenuNavigationControllerDelegate プロトコルで、サイドメニュー表示時に coverView を表示させ、非表示時に取り除きます。

ViewController.swift
extension ViewController: SideMenuNavigationControllerDelegate {
    func sideMenuWillAppear(menu: SideMenuNavigationController, animated: Bool) {
        navigationController?.view.addSubview(coverView)
    }

    func sideMenuWillDisappear(menu: SideMenuNavigationController, animated: Bool) {
        coverView.removeFromSuperview()
    }
}

navigationControlleraddSubView() することによって、画面全体を coverView で覆っています。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?