控制器和视图

我喜欢用代码编写UI,并且使用“自动布局”功能很容易。 但是,这给ViewController留下了大量代码。 我们可以做的一种方法是通过使用专用视图在MVC中将VC分开。 感谢我的朋友Vadym向我展示了它。

我们可以使用generic来做到这一点,即初始化一个视图并替换该view ,我们称其为root

 导入UIKitclass BaseController :UIViewController { 
让root = T()覆盖func loadView(){
视图=根
}
}

现在我们可以有一个UIView子类,例如LoginView

 最后一课LoginView:UIView { 
惰性var textField:UITextField = UITextField()。然后{
$ 0.textAlignment = .center
$ 0.borderStyle = .roundedRect
$ 0.keyboardType = .phonePad
}懒惰的var按钮:UIButton = UIButton()。然后{
$ 0.setTitleColor(.black,for:.normal)
$ 0.backgroundColor = .lightGray
}覆盖init(框架:CGRect){
super.init(frame:frame)addSubviews(
文本域,
纽扣
)约束
textField.centerXAnchor.constraint(equalTo:textField.superview!.centerXAnchor),
textField.centerYAnchor.constraint(equalTo:textField.superview!.centerYAnchor),
textField.widthAnchor.constraint(等于:textField.superview!.widthAnchor,常数:-20),button.topAnchor.constraint(equalTo:textField.bottomAnchor,常数:20),
button.centerXAnchor.constraint(equalTo:button.superview!.centerXAnchor),
button.widthAnchor.constraint(equalTo:textField.widthAnchor,乘数:0.8),
button.heightAnchor.constraint(equalToConstant:44)

}是否需要初始化?(编码器aDecoder:NSCoder){
致命错误()
}
}

然后是LoginController

 最后的类LoginController:BaseController  { 
覆盖func viewDidLoad(){
super.viewDidLoad()view.backgroundColor = .white let gr = UITapGestureRecognizer(目标:自我,行动​​:#selector(viewTapped))
root.addGestureRecognizer(gr)root.button.setTitle(“ Login”,用于:.normal)
root.button.addTarget(self,action:#selector(loginButtonTouched),用于:.touchUpInside)
root.button.isEnabled =否
root.button.showsTouchWhenHighlighted = true root.textField.placeholder =“电话号码”
root.textField.delegate =自我
root.textField.text = dependencyContainer.phoneService.prefix
root.textField.addTarget(self,action:#selector(textFieldDidChange),for:.editingChanged)
}
}

这就是我们声明LoginController

 让loginController = LoginController() 
navigationController.viewControllers = [loginController]

原始故事https://github.com/onmyway133/blog/issues/37