0
1

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

delegateを使って、カスタムviewから画面遷移する

Posted at

はじめに

業務でカスタムviewから画面遷移を行いたい場面がありました。
その時に今まで理解が曖昧だったデリゲートを使う機会があり、
理解が少し明確になったので紹介します。

環境

macOS Big Sur 11.5.2
Xcode 12.5.2
Swift 5.4.2

ゴール

画面Aには、カスタムビューで実装されたボタンがあります。
今回は、カスタムビューで実装されたボタンがタップされたタイミングで画面Bに遷移したいです。

概要

デリゲートを使ってゴールを実現します。
ざっくり次のような手順で実装を進めます。
まず、CustomViewにプロトコルを定義します。
ボタンがタップされたタイミングでデリゲートメソッドが実行されることを定義します。
そして、デリゲートメソッドの実装はViewControllerへ委譲します。

具体的な実装

  1. カスタムビューにプロトコルを定義します。
CustomView.swift
protocol CustomViewDelegate {
  didTapButton()
}
  1. ボタンがタップされた時にデリゲートメソッドが実行されることを定義します。
CustomView.swift
@IBAction func tapButton(_ sender: UIButton) {
  delegate?.didTapButton()
}
  1. 処理の中身の実装をViewController.swiftに委譲します
ViewController.swift
override func viewDidLoad() {
  super.viewDidLoad()
        
  let customView = CustomView()
  customView.delegate = self
}
  1. デリゲートメソッドの中身を実装します。
ViewController.swift
extension ViewController: CustomViewDelegate {
  func didTapButton() {
    guard
      let nav = navigationController,
      let secondVC = storyboard?.instantiateViewController(identifier: "second")
    else { return }
    nav.pushViewController(secondVC, animated: true)
  }
}

まとめ

メソッドを実行するタイミングをCustomViweで定義して、
実装はViewControllerに委譲(デリゲート)する。
今まで曖昧だったデリゲートという概念を少し掴めた感じがしました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?