From 143a4ea4ebd11f2d9ed8c0b409433bbc6ee58ea4 Mon Sep 17 00:00:00 2001 From: David Chavez Date: Tue, 2 Jan 2024 23:37:33 +0100 Subject: [PATCH] feature(uiview): Add extension to find parent view controller (#21) --- .../DSKit/UIKit/UIView/UIView+Parent.swift | 21 +++++++++++++ Tests/DSKitTests/UIView/UIView+Parent.swift | 31 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 Sources/DSKit/UIKit/UIView/UIView+Parent.swift create mode 100644 Tests/DSKitTests/UIView/UIView+Parent.swift diff --git a/Sources/DSKit/UIKit/UIView/UIView+Parent.swift b/Sources/DSKit/UIKit/UIView/UIView+Parent.swift new file mode 100644 index 0000000..396e697 --- /dev/null +++ b/Sources/DSKit/UIKit/UIView/UIView+Parent.swift @@ -0,0 +1,21 @@ +// +// UIView+Parent.swift +// DSKit +// +// Created by David Chavez on 13/1/20. +// + +import UIKit + +extension UIView { + var parentViewController: UIViewController? { + var parentResponder: UIResponder? = self + while parentResponder != nil { + parentResponder = parentResponder?.next + if let viewController = parentResponder as? UIViewController { + return viewController + } + } + return nil + } +} diff --git a/Tests/DSKitTests/UIView/UIView+Parent.swift b/Tests/DSKitTests/UIView/UIView+Parent.swift new file mode 100644 index 0000000..3618a63 --- /dev/null +++ b/Tests/DSKitTests/UIView/UIView+Parent.swift @@ -0,0 +1,31 @@ +// +// UIView+Parent.swift +// DSKit +// +// Created by David Chavez on 1/2/24. +// + +import XCTest +import UIKit +@testable import DSKit + +class ParentViewControllerTests: XCTestCase { + func testParentViewControllerSimpleCase() { + let parent = UIViewController() + let child = UIView() + parent.view.addSubview(child) + + XCTAssert(child.parentViewController === parent) + } + + func testParentViewControllerNestedCase() { + let parent = UIViewController() + let child = UIView() + let grandChild = UIView() + + parent.view.addSubview(child) + child.addSubview(grandChild) + + XCTAssert(grandChild.parentViewController === parent) + } +}