[iOS] 햄버거 메뉴 만드는 법

9160 단어 Swift

간단하게 햄버거 메뉴(Swift) 만들기


Storyboard 설정


(1) segue에서 "Present Modally"를 선택하여 뷰 컨트롤러를 연결합니다.
(2) segue의 "Identifier"를 showMenu로 설정합니다.
(3) segue의 Transition을 Cross Dissolve로 설정합니다.
(4) 메뉴 화면의 회색 부분(View)의 백그라운드를'Opacity'50% 정도로 설정한다.
(5) 회색 섹션의 "tag"을 1로 설정


코드


호출자
import UIKit

class BaseViewController: UIViewController {

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

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

    // ハンバーガーメニューボタンタップ処理
    @IBAction func tapMenu(_ sender: UIBarButtonItem) {
        self.performSegue(withIdentifier: "showMenu", sender: nil)
    }

}
햄버거 메뉴
import UIKit

class MenuViewController: UIViewController {

    @IBOutlet weak var menuView: UIView!

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

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // メニュー画面の位置
        let menuPosition = self.menuView.layer.position
        // 初期位置設定
        self.menuView.layer.position.x = -self.menuView.frame.width
        // 表示アニメーション
        UIView.animate(
            withDuration: 0.1,
            delay: 0,
            options: .curveEaseOut,
            animations: {
                self.menuView.layer.position.x = menuPosition.x
        },
            completion: { bool in
        })

    }

    // メニュー外をタップした場合に非表示にする
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        for touch in touches {
            if touch.view?.tag == 1 {
                UIView.animate(
                    withDuration: 0.2,
                    delay: 0,
                    options: .curveEaseIn,
                    animations: {
                        self.menuView.layer.position.x = -self.menuView.frame.width
                },
                    completion: { bool in
                        self.dismiss(animated: true, completion: nil)
                }
                )
            }
        }
    }

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

}

좋은 웹페이지 즐겨찾기