Home > Enterprise >  Why my app is crashing after opening new controller?
Why my app is crashing after opening new controller?

Time:07-26

This is my image with code

My app is launching and after clicking on new controller crashed. My error is Thread 1: EXC_BAD_ACCESS (code=2, address=0x1d27fc844) Error is in this line NSLayoutConstraint.activate(constants)

 var dimmedBaclroundView : UIView {
    let view = UIView()
    
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
    return view
}

lazy var CView = CustomView { [weak self] in
    guard let self = self else {return}
    self.dismiss(animated: true, completion:  nil)
    
}

init() {
    super.init(nibName: nil, bundle: nil)
    modalPresentationStyle = .overCurrentContext
    modalTransitionStyle = .crossDissolve
    
}

required init?(coder:NSCoder) {
    fatalError("init(coder :) has not been implanted")
}



override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(dimmedBaclroundView)
    view.addSubview(CView)
    
    
    var constants = [
        dimmedBaclroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        dimmedBaclroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        dimmedBaclroundView.topAnchor.constraint(equalTo: view.topAnchor),
        dimmedBaclroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ]
    
    constants.append(contentsOf: [
        CView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
        CView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor),
        CView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 10),
        CView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 0.3)
    ])
    
    NSLayoutConstraint.activate(constants) //Here is my error
}

CodePudding user response:

Your view should not be a computed property, you should only initialize it once when viewcontroller initialize, like this:

var dimmedBaclroundView : UIView = {
    let view = UIView()
    
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
    return view
}()

Crashing happen probably because it cannot find the previous instance of dimmedBaclroundView because it got created again after every call, also you should fix the name..

  • Related