最好的方法是什么(例如)一次在多个View Controllers中包含一行(例如,在每个VC中包含ViewDidLoad下的一行代码)?
我正在寻找一种更有效的方法,而不仅仅是在10个不同的VC中复制粘贴
答案 0 :(得分:5)
继承会帮助你:
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// your settings for all view controllers here:
self.view.backgroundColor = UIColor.lightGrayColor()
}
}
class HomeViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad() // call code from BaseViewController.viewDidLoad()
}
}
class ChatViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad() // call code from BaseViewController.viewDidLoad()
}
}
class ProfileViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad() // call code from BaseViewController.viewDidLoad()
}
}
另一种选择是Swift扩展:
extension UIViewController {
func configureView() {
self.view.backgroundColor = UIColor.lightGrayColor()
}
}
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
}
class ChatViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
}
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
}
有关Swift中的Inheritance和Extensions的更多信息