LoginSignup
50
52

More than 5 years have passed since last update.

サイドから出てくるスワイプメニューを作る

Posted at

アプリ画像

やったこと

  • GmailとかFacebookとか、スマホアプリでよくある、左とか右にスワイプしたら、メニューが出てくる、逆向きにスワイプしたら戻るやつを作る。
  • メニューが出ている間は、メイン部分の上に透明ボタンを被せる。
  • 透明ボタンを押すと、メニューを閉じる。

コード

ViewController.swift

class ViewController: UIViewController {

    // フロントビュー
    @IBOutlet var frontView: UIView!

    // カバーボタン(透明)
    @IBOutlet var coverButton: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // カバーボタンを隠す
        self.coverButton.hidden = true
    }

    // スワイプ(メニューを表示、非表示)
    @IBAction func swipeView(sender: UISwipeGestureRecognizer) {

        var location:CGPoint = self.frontView.center;
        var center_x:CGFloat = self.view.center.x;

        //スワイプした方向で分岐
        if (sender.direction == UISwipeGestureRecognizerDirection.Right) {
            // 右に開ける
            location.x = center_x + 120
            // カバーボタンを表示
            self.coverButton.hidden = false
        } else {
            //左に閉じる
            location.x = center_x
            // カバーボタンを隠す
            self.coverButton.hidden = true
        }
        UIView.animateWithDuration(
            0.2,
            delay:0.5,
            options : UIViewAnimationOptions.CurveEaseIn,
            animations : {
                self.frontView.center = location
            },
            completion: {
                (value: Bool) in
                println("");
            }
        )

    }

    // カバーボタンをタップするとメニューを閉じる
    @IBAction func closeMenu(sender: UIButton) {

        var location:CGPoint = self.frontView.center;
        var center_x:CGFloat = self.view.center.x;

        //左に閉じる
        location.x = center_x
        // カバーボタンを隠す
        self.coverButton.hidden = true

        UIView.animateWithDuration(
            0.2,
            delay:0.5,
            options : UIViewAnimationOptions.CurveEaseIn,
            animations : {
                self.frontView.center = location
            },
            completion: {
                (value: Bool) in
                println("");
            }
        )

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

コツとか

  • Recognizerなどの名前を変えるのに、コツが要る 名前を変える

ツリーから名前を変えるんだけど、最初は、編集状態にする方法がよく分からなかった。選択してから、短いクリックをする。ダブルクリックではできない。
* iosシミュレーターでスワイプするときは、普通にマウスでドラッグする。

ソースアップ

コメント

  • animateWithDurationの書き方はすごい適当で、こちらを参考にしました。
    http://qiita.com/skatata/items/a0b908c899748c843db3

  • SwipeCatという名前で犬の写真にしてしまった。

  • 始めはMenu2だけ前に出てしまって、作りなおしたら直ったけどよくわからない。

  • 共通処理をまとめてあげたい。

50
52
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
50
52