0
4

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 5 years have passed since last update.

デリゲートは部品を使いまわしたい時に使うと便利

0
Last updated at Posted at 2020-10-29

デリゲートをようやくわかったので備忘録。

ボタンなど、小さな部品を使いまわしたいけれど、ページごとに違う処理をさせたい時に使うと便利。

今回は下のボタン群を使い回す。左から「戻るボタン」「解説ボタン」「次へボタン」。このボタンクラスをいろんなページで使いまわしたい。

デリゲート.png

[やりたいこと]
ページごとにボタン押下のアクションを切り替えたい。
戻るボタンを押すと、とあるページでは前画面に遷移、他のページではモーダルを終了させる。はたまた他のページでは保存処理をしてからページを終了させたい。などなど

[解決方法]
各々のページにボタン押下のアクションを書く。ボタンのデザイン部分は共通化してもよいが、アクション部分の機能は各々のページにデリゲートする。これが「移譲」と訳されるデリゲートの役割である。

[やり方]
1、ボタン部分のViewにプロトコルを書く。
footerViewクラスのボタンを使いたかったら、必ず決められたメソッド名を使って実装してねというお約束。

FooterView.swift
protocol TapLeftButtonVCDelegate {
    func tapLeftButton()
}
protocol TapCenterButtonVCDelegate {
    func tapCenterButton()
}
protocol TapRightButtonVCDelegate {
    func tapRightButton()
}

2、各々のページで、ボタンクラスをインスタンス化し、ボタンアクションのデリゲート先が自分であることを宣言。

ViewController.swift
    // このページでは右ボタンだけ使いたいので右ボタンのプロトコルのみ宣言。
    @IBOutlet weak var footerView: FooterView!
    override func viewDidLoad() {
        super.viewDidLoad()
        footerView.tapRightButtonVCDelegate = self
    }

3、各々のページでボタン押下後のアクションを実装。

extension ViewController: TapRightButtonVCDelegate {
    func tapRightButton() {
        // 次の画面にすすむ処理、保存処理、なんでも好きなように書く
    }
}

4、最後にボタンのFooterViewに戻り、ボタンを押したらデリゲート先の処理を行うように指示。

class FooterView: UIView {
    var tapRightButtonVCDelegate: TapRightButtonVCDelegate?

    @IBAction func tapRightButton(_ sender: Any) {
        tapRightButtonVCDelegate?.tapRightButton()
    }
}

これで、ボタンをいろんなページで使い回すことができます。

[感想]
用途から考えるデリゲートの使い方でした。他にも便利な使い方があるかも。

0
4
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
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?