tableView + navigationController

f:id:hayateasdf:20171208102427g:plain

1 Storyboardで画面作成

  • 赤画面のStoryboard ID -> TableCell1
  • 青画面のStoryboard ID -> TableCell2
  • セルのIdentifier -> Cell

f:id:hayateasdf:20171208102453p:plain

2 UIViewControllerをUITableViewCellを作成 -> Classを接続

3 コードを書く

import UIKit

class TableViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    let ids = [
        "TableCell1",
        "TableCell2",
    ]
    var cacheControllers: [String: UIViewController] = [:]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableInit()
        
        for id in ids {
            cacheControllers[id] = storyboard?.instantiateViewController(withIdentifier: id)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension TableViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableInit() {
        tableView.dataSource = self
        tableView.delegate = self
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ids.count * 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
        
        cell.title.text = ids[indexPath.row % ids.count]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
        
        let controller = cacheControllers[cell.title.text!]
        controller?.title = cell.title.text!
        navigationController?.pushViewController(controller!, animated: true)
    }
}
import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var title: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}