我不是使用故事板編程的新手。我想要做的是移動負責初始化UIView和約束的代碼,從那裏我也想把它們放在另一個文件中。是否可以在ViewController文件之外設置約束和對象?
理想情況下,我想有一個呼叫
view.addSubview(loginControllerObjects(幀:view.frame))
從我的viewDidLoad()的調用單獨的文件,並設置對象放置在適當的位置,以保持我的ViewController空閒。
我已經解決了大部分問題,但它似乎就像我的函數setUpInputContainer()給我「終止於類型爲NSException的未捕獲異常」錯誤。建議它由於它的錨定引用了不同視圖層次中的項目。有誰知道如何解決這個問題?
應用代表
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let homeViewController = ViewController()
window?.rootViewController = UINavigationController(rootViewController: homeViewController)
window!.makeKeyAndVisible()
return true
}
視圖控制器
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
view.addSubview(loginControllerContraints(frame: view.frame))
}
}
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
}
}
LoginControllerContraints
class loginControllerContraints: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(r: 61, g: 91, b: 151)
setUpInputContainer()
addSubview(inputsContainerView)
}
let inputsContainerView: UIView = {
let view = UIView()
let red = UIColor.red
view.backgroundColor = UIColor.white
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5
view.layer.backgroundColor = red.cgColor
view.layer.masksToBounds = true
return view
}()
var inputsContainerViewHeightAnchor: NSLayoutConstraint?
func setUpInputContainer() {
//Needs x, y, height, and width constraints for INPUTCONTAINER
inputsContainerView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: widthAnchor, constant: -24).isActive = true
inputsContainerViewHeightAnchor = inputsContainerView.heightAnchor.constraint(equalToConstant: 150)
inputsContainerViewHeightAnchor?.isActive = true
}
//Required do not touch
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
哇,不敢相信我錯過了。感謝您的明確迴應。 –
歡迎@ChandlerLong;) – trungduc