Allow install and uninstall to be indempotent

This commit is contained in:
Robert Payne 2015-02-17 13:41:45 +13:00
parent 2701293432
commit faf7d43aaf
2 changed files with 35 additions and 6 deletions

View File

@ -287,11 +287,6 @@ public class Constraint {
// MARK: internal // MARK: internal
internal func installOnView(updateExisting: Bool = false) -> Array<LayoutConstraint> { internal func installOnView(updateExisting: Bool = false) -> Array<LayoutConstraint> {
if self.installedOnView != nil {
NSException(name: "Cannot Install Constraint", reason: "Already installed", userInfo: nil).raise()
return []
}
var installOnView: View? = nil var installOnView: View? = nil
if self.toItem.view != nil { if self.toItem.view != nil {
installOnView = Constraint.closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view) installOnView = Constraint.closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view)
@ -306,13 +301,21 @@ public class Constraint {
installOnView = self.fromItem.view installOnView = self.fromItem.view
} }
if installedOnView == nil { if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "Missing superview", userInfo: nil).raise() NSException(name: "Cannot Install Constraint", reason: "Missing superview", userInfo: nil).raise()
return [] return []
} }
} }
} }
if self.installedOnView != nil {
if self.installedOnView != installOnView {
NSException(name: "Cannot Install Constraint", reason: "Already installed on different view.", userInfo: nil).raise()
return []
}
return self.installedLayoutConstraints?.allObjects as Array<LayoutConstraint>
}
var newLayoutConstraints = Array<LayoutConstraint>() var newLayoutConstraints = Array<LayoutConstraint>()
let layoutFromAttributes = self.fromItem.attributes.layoutAttributes let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
let layoutToAttributes = self.toItem.attributes.layoutAttributes let layoutToAttributes = self.toItem.attributes.layoutAttributes

View File

@ -140,4 +140,30 @@ class SnapTests: XCTestCase {
} }
func testReinstallConstraints() {
let v1 = UIView()
let v2 = UIView()
self.container.addSubview(v1)
self.container.addSubview(v2)
let constraints = v1.snp_prepareConstraints { (make) -> Void in
make.edges.equalTo(v2)
return
}
XCTAssertEqual(self.container.constraints().count, 0, "Should have 0 constraints installed")
for constraint in constraints {
constraint.install()
}
XCTAssertEqual(self.container.constraints().count, 4, "Should have 4 constraints installed")
for constraint in constraints {
constraint.install()
}
XCTAssertEqual(self.container.constraints().count, 4, "Should have 0 constraints installed")
}
} }