From faf7d43aaf6c46d11d1b1cdbb9ff58392ece6e52 Mon Sep 17 00:00:00 2001 From: Robert Payne Date: Tue, 17 Feb 2015 13:41:45 +1300 Subject: [PATCH] Allow install and uninstall to be indempotent --- Snap/Constraint.swift | 15 +++++++++------ SnapTests/SnapTests.swift | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/Snap/Constraint.swift b/Snap/Constraint.swift index 2465af8..59676ff 100644 --- a/Snap/Constraint.swift +++ b/Snap/Constraint.swift @@ -287,11 +287,6 @@ public class Constraint { // MARK: internal internal func installOnView(updateExisting: Bool = false) -> Array { - if self.installedOnView != nil { - NSException(name: "Cannot Install Constraint", reason: "Already installed", userInfo: nil).raise() - return [] - } - var installOnView: View? = nil if self.toItem.view != nil { installOnView = Constraint.closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view) @@ -306,13 +301,21 @@ public class Constraint { installOnView = self.fromItem.view } - if installedOnView == nil { + if installOnView == nil { NSException(name: "Cannot Install Constraint", reason: "Missing superview", userInfo: nil).raise() 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 + } + var newLayoutConstraints = Array() let layoutFromAttributes = self.fromItem.attributes.layoutAttributes let layoutToAttributes = self.toItem.attributes.layoutAttributes diff --git a/SnapTests/SnapTests.swift b/SnapTests/SnapTests.swift index 5a82a13..50b41ca 100644 --- a/SnapTests/SnapTests.swift +++ b/SnapTests/SnapTests.swift @@ -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") + } + }