Search code examples
iosswiftuitableviewsnapkit

Update constraint does not work on UITableView snapkit


When I try to update the snapkit constraint right after making the constraint I get aUpdated constraint could not find existing matching constraint to update error. The code I am using is below:

let directionList = UITableView()
directionList.delegate = self
directionList.dataSource = self
directionList.tag = DIRECTIONS_TABLE_TAG
self.view.addSubview(directionList)
directionList.snp.makeConstraints{ (make) -> Void in
    make.width.equalToSuperview()
    make.top.equalTo(self.view.snp.bottom)
    make.left.equalToSuperview()
    make.right.equalToSuperview()
    make.bottom.equalToSuperview().offset(-20)
}

directionList.snp.updateConstraints { (make) -> Void in
   make.top.equalTo(self.topDarkBlue.snp.bottom)
}

Solution

  • The documentation says that updateConstraints is only for updating the constants of existing constraints.

    Alternative if you are only updating the constant value of the constraint you can use the method snp.updateConstraints instead of snp.makeConstraints

    You are not updating the constant; you are trying to assign the constraint to a new anchor.

    I think what you should do is take a reference to the top constraint:

    var topConstraint: Constraint? = nil
    ...
    topConstraint = make.top.equalTo(self.view.snp.bottom)
    

    later remove the top constraint:

    topConstraint.uninstall()
    

    Then use another block to make the new constraint.

    directionList.snp.makeConstraints{ (make) -> Void in
       make.top.equalTo(self.topDarkBlue.snp.bottom)
    }