Home > database >  Creating a UIView in a separate class and installing constrains
Creating a UIView in a separate class and installing constrains

Time:03-04

ViewController:

class ViewController: UIViewController, ViewSpecificController {
typealias RootView = CustomView
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view().configure()
    }

    override func loadView() { self.view = CustomView() }
}

UIView:

class CustomView: UIView {
    func configure() {
        backgroundColor = .orange
        translatesAutoresizingMaskIntoConstraints = false
        addConstraints()
        
    }
    func addConstraints() {
        var constraints = [NSLayoutConstraint]()
        constraints.append(self.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor))
        constraints.append(self.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor))
        constraints.append(self.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor))
        constraints.append(self.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor))
        NSLayoutConstraint.activate(constraints)
    }
}

Executing this code results in an error "[LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want." I tried to initialize UIView, the same error appeared there. How to fix it?

CodePudding user response:

From what i can see it looks like your CustomView class is trying to set constraints to itself. The constraints aren't needed as the ViewController will handle sizing it automatically once you replace the original in loadView(). Removing your addConstraints() method from configure() should solve your problem. See if that works...

  • Related