LoginSignup
1
1

More than 1 year has passed since last update.

デリゲートメソッドを作成 -swift

Posted at

◉デリゲートとは
 プロコトルを用いたデザインパターンで「他のクラスのインスタンスに、処理を任せることができる」もの

◉主役
・プロトコル
・処理を任せるクラス
・処理を任せられるクラス
 ex)
UITableViewを表示するUIViewControllerがあるとする。
  UITableViewだけではUIとして完成しない(セルやセルの数自体がない為)
・プロトコル→UITableViewDelegateとUITableViewDataSource
・処理を任せるクラス→UITableView
・処理を任せられるクラス→UIViewController

◉デリゲートメソッド作成・使用方法
①プロトコールの作成

protocol プロトコール名 {
 //規則のみ定める
  func メソッド名(引数:外部引数)
}

②プロトコールを変数化して使えるようにする

var 変数名:プロトコール名?

③任意のタイミングで発動

@IBAction func Action名(_ sender: Any) {
   //処理を任せるクラスで発動させる
     変数名.メソッド名(引数:外部引数)
}

④処理を任せられるクラスでプロトコールを宣言

class ViewController: UIViewController,プロトコール名 {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
}

⑤プロトコールに書かれたメソッドを記述

 func メソッド名(引数:外部引数) {
    //外部引数には処理を任せるクラスの変数の値が入っている
 }

⑥ 処理を任せるクラスから処理を任せられるクラスへ委任を受ける

override func prepare(for segue:UIStoryboard,sender:Any?) {
    let 変数 = segue.instination as! 処理を任せるクラス
    変数.プロトコールの変数名 = self
}
1
1
1

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