また1からこつこつと

最高はひとつじゃないと信じてまたがんばります。

【Swift3】UITableViewCellをタップしたときに画面遷移をさせる

このブログで1番読まれてる記事がこれ
mjk0513.hateblo.jp

これはSwift1.x系での記法のままなので新しくSwift3.x系で書き直します。

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
	
	let myTableView:UITableView = UITableView()

	let items:[String] = ["北海道", "青森", "秋田", "岩手", "福島", "宮城", "山形"]
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		myTableView.frame = self.view.bounds
		myTableView.dataSource = self
		myTableView.delegate = self
		myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
		self.view.addSubview(myTableView)
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}

	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return items.count
	}
	
	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let cell:UITableViewCell = UITableViewCell(style: .default, reuseIdentifier: "MyCell")
		cell.textLabel?.text = items[indexPath.row]
		return cell
	}
	
	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		//セルの選択解除
		tableView.deselectRow(at: indexPath, animated: true)
		
		//ここに遷移処理を書く
		self.present(SecondViewController(), animated: true, completion: nil)
	}

}

次に遷移先のViewです
SecondViewController.swfit

import UIKit

class SecondViewController: UIViewController {
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		self.view.backgroundColor = UIColor.white
		
		let backButton:UIButton = UIButton()
		backButton.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
		backButton.setTitle("back", for: .normal)
		backButton.setTitleColor(UIColor.blue, for: .normal)
		backButton.layer.position = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
		backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
		self.view.addSubview(backButton)
		
	}
	
	func back() {
		self.dismiss(animated: true, completion: nil)
	}
	
}

ポイントはdidSelectRowAtというメソッドを呼び出して、その中に遷移する処理を書くことです。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
	//セルの選択解除
	tableView.deselectRow(at: indexPath, animated: true)
		
	//ここに遷移処理を書く
	self.present(SecondViewController(), animated: true, completion: nil)
}

ちなみに、tableView.deselectRow()をやらないとAppleの審査通らないので注意です。
これがSwift3での画面遷移処理でした!