Button→Controllerに画面遷移させる(コード量が少し減る)
実行環境
Swift5
Xcode Version 10.2.1
前提条件
構造体がある(今回はPerson)
MainControllerに何か特定のButtonが配置されている(今回は4つbuttonがある)
SubControllerが4つある
動作としては特定のbuttonを押した時に特定の別のcontrollerに画面遷移させる
(ex: ●を押したら、1controllerへ画面遷移)
● → 1controller
▲ → 2controller
■ → 3controller
★ → 4controller
mainController.Swift
import UIKit
//@IBOutlet等の記述は省略しています
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case Segue.one.rawValue:
if let destination = segue.destination as? oneVC {
destination.person = person
}
case Segue.two.rawValue:
if let destination = segue.destination as? toTwoVC {
destination.person = person
}
case Segue.three.rawValue:
if let destination = segue.destination as? toThreeVC {
destination.person = person
}
case Segue.four.rawValue:
if let destination = segue.destination as? toFourVC {
destination.person = person
}
default:
break
}
}
//segueのenum化
enum Segue : String {
case one = "toOne"
case two = "toTwo"
case three = "toThree"
case four = "toFour"
}
mainController.Swift内のprepare関数内を下記の記述に書き換える
mainController.Swift
if var destination = segue.destination as? PersonProtocol {
destination.person = person
}
//任意のprotocol作成(ここではPersonProtocol)
protocol PersonProtocol {
var person: Person! { get set }
}
mainController以外のファイルにそれぞれ下記を記述
subController.Swift
import UIKit
class OneVC: UIViewController, PersonProtocol { //classにPersonProtocolを追加
var person: Person!
override func viewDidLoad() {
super.viewDidLoad()
print(person.name)//terminal確認表示(Person構造体がnameを持っている)
}