Skip to content

Commit

Permalink
added disabling/enabling of height and width anchors
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolaischneider committed Jan 13, 2024
1 parent 82f9ee2 commit 2cfcffa
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions Sources/SimpleConstraints/ConstraintAnchor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 24 additions & 0 deletions Sources/SimpleConstraints/Extensions/UIView+Helper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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
}
}

0 comments on commit 2cfcffa

Please sign in to comment.