Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active March 14, 2019 01:57
Show Gist options
  • Save KentarouKanno/44bf5dc75f17b58bfb0d to your computer and use it in GitHub Desktop.
Save KentarouKanno/44bf5dc75f17b58bfb0d to your computer and use it in GitHub Desktop.
UIGestureRecognizerDelegate

UIGestureRecognizerDelegate

★ UIGestureRecognizerDelegateプロトコルを採用する

class ViewController: UIViewController,UIGestureRecognizerDelegate { }

★ action:で設定した関数が呼ばれる前に呼ばれる関数

func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {

    // true: 設定した関数が呼ばれる false: 呼ばれない
    return true
}

★ 複数のジェスチャーを認識できるようにする

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        
    // true: 認識する false: 認識しない
    return true
}

☆ Swipeで戻るの有効無効を切り替える

import UIKit

final class ViewController1: UIViewController, UIGestureRecognizerDelegate {
    
    @IBOutlet private weak var editButton: UIButton!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.delegate = self
    }
    
    @IBAction private func backAction(_ sender: UIButton) {
        showAlertCheck()
    }
    
    private func showAlert() {
        let alert = UIAlertController(title: "", message: "編集中です、戻りますか?", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { _ in
            self.navigationController?.popViewController(animated: true)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .default) { _ in }
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    }
    
    private func isEditing() -> Bool {
        return editButton.isSelected ? true : false
    }
    
    public func showAlertCheck() {
        if isEditing() {
            showAlert()
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if isEditing() {
            showAlert()
        }
        return !isEditing()
    }

    @IBAction func editAction(_ sender: UIButton) {
        sender.isSelected.toggle()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment