/// Swaps the display order of two child view controllers within their parent view controller. /// /// This method is used to adjust the z-ordering of the views associated with two child view controllers. /// It's particularly useful when the two child view controllers are embedded in a common parent view controller and you want to change which one appears on top. /// /// - Note: /// This method will only adjust the order if both view controllers are children of the same parent view controller. /// If they aren't, the method will have no effect. /// /// - Parameters: /// - vc1: The first view controller whose display order you want to swap. /// - vc2: The second view controller whose display order you want to swap. /// /// - Usage: /// Assuming `self` is the parent view controller: /// ``` /// self.swapViewControllerOrder(childVC1, childVC2) /// ``` func swapViewControllerOrder<T1: UIViewController, T2: UIViewController>(_ vc1: T1, _ vc2: T2) { if let firstIndex = self.children.firstIndex(where: { $0 is T1 }), let secondIndex = self.children.firstIndex(where: { $0 is T2 }) { let firstViewFrame = vc1.view.frame UIView.animate(withDuration: 1, animations: { vc1.view.frame = vc2.view.frame vc2.view.frame = firstViewFrame self.view.exchangeSubview(at: firstIndex, withSubviewAt: secondIndex) }) } }
使い方
UIViewController
のカスタムクラスなどで、
self.swapViewControllerOrder(1つ目のVC, 2つ目のVC)