Skip to content

Commit

Permalink
feature(uiview): Add extension to find parent view controller (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
dcvz authored Jan 2, 2024
1 parent 928dec9 commit 143a4ea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Sources/DSKit/UIKit/UIView/UIView+Parent.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
31 changes: 31 additions & 0 deletions Tests/DSKitTests/UIView/UIView+Parent.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 143a4ea

Please sign in to comment.