使用 BaseViewController 并使其成为新视图控制器的父类
如下所示:
基础控制器:
导入 UIKit
class BaseViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
//Common initiation codes
}
// Write all the codes that can be shared between the controllers
}
为每个视图控制器创建单独的类并根据需要修改它们:
class SettingsController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()//This calls everything you wrote as init code for BaseController
//Write any view controller specific init code here
}
//If you have any other settings controller specific code, write here
}
由于我没有看到你的代码,我不能确定这是否是正确的方法。这种方法仍然意味着您不必为每个视图控制器类重写代码并且仍然保持干净。
当您通过代码进行布局和视图时,首选上述方法。
如果您使用故事板并且根据您的具体需要,我建议您改为这样做:
//Initiate your controller like this from the previous controller
@IBAction func goToSettingsController(_ sender: Any) {
let baseController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ControllerID") as! BaseController
baseController.id = "Settings"
self.present(baseController, animated: true, completion: nil)
}
@IBAction func goToAboutController(_ sender: Any) {
let baseController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ControllerID") as! BaseController
baseController.id = "About"
self.present(baseController, animated: true, completion: nil)
}
在你的 BaseController 中:
类 BaseController: UIViewController{
var id: String!
@IBOutlet weak var backGround: UIView!
override func viewDidLoad() {
super.viewDidLoad()
customInit()
}
func customInit(){
switch id{
case "Settings":
self.backGround.backgroundColor = .purple //Any controller specific code
break
case "About":
self.backGround.backgroundColor = .green //Any controller specific code
break
default:
break
}
}
}
您不需要前面提到的三个单独的类,但您可以为两个 ViewController 使用 BaseController 类。