0
0

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.

[Swift5] TableViewCell 別のStoryBoardに遷移する方法

Posted at

イメージ

手順

①TableViewCellのIdentifierを設定する(名前はなんでもOK)

②遷移先StoryBoardのStoryBoardIDを設定する

後述の withIdentifier: "" に入る箇所である。

③遷移元ControllerのDelegateに以下を記載する。
・遷移先StoryBoardの取得
・遷移先StoryBoardのStoryBoardIDを記載
・pushViewControllerで遷移処理を記載

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 遷移先のStoryBoardを取得("Sub"はSub.storyboardのSub)
        let SubStoryBoard:UIStoryboard = UIStoryboard(name: "Sub", bundle: nil)
        switch indexPath.row {
        case 0:
            // widthIdentifierには遷移先StoryBoardに設定したStoryBoardIDを記載する
            let targetViewController = SubStoryBoard.instantiateViewController(withIdentifier: "sub")
            // navigationControllerを設定していないと遷移しないので注意
            self.navigationController?.pushViewController(targetViewController, animated: true)
        default:
            break
        }
    }
}

全体

ViewController(遷移元)

import UIKit

struct tableData {
    var id: Int
    var name: String
}

private let tableList: [tableData] = [
    tableData.init(id: 1, name: "テストA"),
    tableData.init(id: 2, name: "テストB"),
    tableData.init(id: 3, name: "テストC")
]

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = tableList[indexPath.row].name
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let SubStoryBoard:UIStoryboard = UIStoryboard(name: "Sub", bundle: nil)
        switch indexPath.row {
        case 0:
            let targetViewController = SubStoryBoard.instantiateViewController(withIdentifier: "sub")
            self.navigationController?.pushViewController(targetViewController, animated: true)
        default:
            break
        }
    }
}

参考にさせていただいた記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?