3
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 1 year has passed since last update.

【Swift】CustomViewをタップしたら画面遷移したい

Last updated at Posted at 2023-05-15

はじめに

こちらの記事を参考に、MapViewとCustomViewを作成したのですが、そこから「CustomViewをタップしたら画面遷移」したくなったのでやってみました。

参考記事に記載されているCustomViewUIViewなので、画面遷移処理をかけません。

PlaceCalloutView.swift
import UIKit

final class PlaceCalloutView: UIView {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imageView: UIImageView!

    @IBAction func buttonDidTap(_ sender: Any) {
        print("button was tapped")
    }
}

さて、どうしたもんか。

実装

対応策としてはDelegateを使って「UIViewにできないことはUIViewControllerに任せちゃおう」ということにしました。

PlaceCalloutView.swift
import UIKit

final class PlaceCalloutView: UIView {    
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var viewButton: UIButton!
    var delegate: PlaceCalloutViewDelegate? = nil
    
    @IBAction func tepedViewButton(_ sender: Any) {
        self.delegate?.showNextView()
    }
}

protocol PlaceCalloutViewDelegate {
    func showNextView()
}
TopViewController.swift
import UIKit

class TopViewController: UIViewController {
    // 省略
}

extension TopViewController: PlaceCalloutViewDelegate {
    func showNextView() {
        // 画面遷移処理
        let storyboard = UIStoryboard(name: "NextView", bundle: nil)
        let nextVC = storyboard.instantiateViewController(withIdentifier: "NextView") as! NextViewController
        self.present(congestionGraphVC, animated: false)
    }
}

まとめ

Delegateの使い方としてより良い使い方等ありましたら、ご指摘願います。

3
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
3
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?