Skip to content

Commit

Permalink
🛠 Refactor: Update UIView+Helpers
Browse files Browse the repository at this point in the history
Related:
* TODO:2023-03-04-06-34-28 - Library Native Cleanup

Summary:
* Clean-up/re-write extension function `UIView.removeAllConstraints` from `UIView+Helpers`.
* Rename `UIView.removeAllConstraints` to `removeAllAncestorConstraints`.
  • Loading branch information
dominicstop committed Mar 24, 2023
1 parent fb89e8f commit 13cf593
Showing 1 changed file with 32 additions and 16 deletions.
48 changes: 32 additions & 16 deletions ios/src_library/Extensions/UIView+Helpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,41 @@ extension UIView {
return nil
};

// From: https://stackoverflow.com/questions/24418884/remove-all-constraints-affecting-a-uiview
// After it's done executing your view remains where it was because it creates autoresizing
// constraints. When I don't do this the view usually disappears. Additionally, it doesn't just
// remove constraints from superview but traversing all the way up as there may be constraints affecting it in ancestor views.
public func removeAllConstraints() {
var _superview = self.superview;
/// Remove all ancestor constraints that are affecting this view instance
///
/// Note: 2023-03-24-00-39-51
///
/// * From: https://stackoverflow.com/questions/24418884/remove-all-constraints-affecting-a-uiview
///
/// * After it's done executing, your view remains where it was because it
/// creates autoresizing constraints.
///
/// * When I don't do this the view usually disappears.
///
/// * Additionally, it doesn't just remove constraints from it's superview,
/// but in addition, it also climbs the view hierarchy, and removes all the
/// constraints affecting the current view instance that came from an
/// ancestor view.
///
public func removeAllAncestorConstraints() {
var ancestorView = self.superview;

while let superview = _superview {
for constraint in superview.constraints {
if let first = constraint.firstItem as? UIView, first == self {
superview.removeConstraint(constraint)
};

if let second = constraint.secondItem as? UIView, second == self {
superview.removeConstraint(constraint);
// Climb the view hierarchy until there are no more parent views...
while ancestorView != nil {
for ancestorConstraint in ancestorView!.constraints {

let constraintItems = [
ancestorConstraint.firstItem,
ancestorConstraint.secondItem
];

constraintItems.forEach {
guard ($0 as? UIView) === self else { return };
ancestorView!.removeConstraint(ancestorConstraint);
};

ancestorView = ancestorView!.superview;
};

_superview = superview.superview;
};

self.removeConstraints(self.constraints);
Expand Down

0 comments on commit 13cf593

Please sign in to comment.