Search code examples
swiftstoryboardtableviewsegue

How to link two view controllers to a programmatically created table view?


Sorry for my bad English.

I want this: When someone click in a cell it opens in another view controller.

I created the table view programmatically.

import UIKit
class BibleBooksViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource {

private let myArray: NSArray = ["Gênesis", "Êxodo", "Levitico"]
private var myTableView: UITableView!
var bibleArray = BibleBooksMock().booksArray

override func viewDidLoad() {
    super.viewDidLoad()

    let barHeight: CGFloat =
UIApplication.shared.statusBarFrame.size.height
    let displayWidth: CGFloat = self.view.frame.width
    let displayHeight: CGFloat = self.view.frame.height

    myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: 
displayWidth, height: displayHeight - barHeight))
    myTableView.register(UITableViewCell.self, forCellReuseIdentifier: 
"MyCell")
    myTableView.dataSource = self
    myTableView.delegate = self
    self.view.addSubview(myTableView)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
Int) -> Int {
    return bibleArray.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: 
IndexPath) -> CGFloat {
    return 70
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 
-> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: 
indexPath as IndexPath)
    cell.textLabel!.text = "\(bibleArray[indexPath.row].title)"
    return cell
 }
}

The output is this:

The code output img from the code

The iOS version is 12.1 The swift version is 4.2


Solution

  • Add this to BibleBooksViewController:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let chapter = bibleArray[indexPath.row]
        var vc = ChapterViewController()
        vc.chapterName = chapter.title
        navigationController?.pushViewController(vc, animated: true)
    }
    

    And define this controller:

    class ChapterViewController: UIViewController {
    
        var chapterName: String?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            title = chapterName
    
            view.backgroundColor = UIColor.white
        }
    
    }
    

    More about tableView(_:didSelectRowAt:) here.