diff --git a/README.md b/README.md index d151538..a722e27 100644 --- a/README.md +++ b/README.md @@ -154,12 +154,14 @@ NSLayoutConstraint.activate([ ## Usage Helper Functions ### Enable/Disable Constraints + You can enbale/disable constraints of a given anchor using `enableConstraint` / `disableConstraint`. The resepctive anchor is passed as a parameter. ```swift view.disableConstraint(for: .top) ``` ### Remove all Constraints + Remove all constraints using `removeAllConstraints()`. ## Contributing diff --git a/Sources/SimpleConstraints/ConstraintAnchor.swift b/Sources/SimpleConstraints/ConstraintAnchor.swift index 546ffb9..19bcc4e 100644 --- a/Sources/SimpleConstraints/ConstraintAnchor.swift +++ b/Sources/SimpleConstraints/ConstraintAnchor.swift @@ -9,6 +9,19 @@ public enum EdgeX: Hashable { case left, right, centerX } +public enum Length { + case height, width + + func anchor (view: UIView) -> NSLayoutDimension { + switch self { + case .height: + return view.heightAnchor + case .width: + return view.widthAnchor + } + } +} + public enum ConstraintYAnchor { case top(UIView, CGFloat) case topSafe(UIView, CGFloat) diff --git a/Sources/SimpleConstraints/Extensions/UIView+Helper.swift b/Sources/SimpleConstraints/Extensions/UIView+Helper.swift index 14173e4..2184974 100644 --- a/Sources/SimpleConstraints/Extensions/UIView+Helper.swift +++ b/Sources/SimpleConstraints/Extensions/UIView+Helper.swift @@ -37,6 +37,18 @@ extension UIView { public func disableConstraint(for anchor: EdgeY) { self.toggleConstraint(for: ConstraintYAnchor(egde: anchor, view: self).anchor, enable: false) } + + /// Enable the constraints of the given anchor + /// - Parameter anchor: height or width anchor + public func enableConstraint(for anchor: Length) { + self.toggleConstraint(for: anchor.anchor(view: self), enable: true) + } + + /// Disable the constraints of the given anchor + /// - Parameter anchor: height or width anchor + public func disableConstraint(for anchor: Length) { + self.toggleConstraint(for: anchor.anchor(view: self), enable: false) + } /// Removes all constraints affecting this view. public func removeAllConstraints() { @@ -79,4 +91,16 @@ extension UIView { $0.firstAnchor == anchor || $0.secondAnchor == anchor }?.isActive = enable } + + private func toggleConstraint(for anchor: NSLayoutDimension, enable: Bool) { + // Find and deactivate the constraint for the specified anchor + constraints.first { + $0.firstAnchor == anchor || $0.secondAnchor == anchor + }?.isActive = enable + + // Also check the superview's constraints + superview?.constraints.first { + $0.firstAnchor == anchor || $0.secondAnchor == anchor + }?.isActive = enable + } }