万年素人からHackerへの道

万年素人がHackerになれるまで殴り書きするぜ。

  • ・資産運用おすすめ
    10万円は1000円くらい利益
    資産運用ブログ アセマネ
    • ・寄付お願いします
      YENTEN:YYzNPzdsZWqr5THWAdMrKDj7GT8ietDc2W
      BitZenny:ZfpUbVya8MWQkjjGJMjA7P9pPkqaLnwPWH
      c0ban:8KG95GXdEquNpPW8xJAJf7nn5kbimQ5wj1
      Skycoin:KMqcn7x8REwwzMHPi9fV9fbNwdofYAWKRo

    2つのUIViewControllerを交換する拡張メソッド

        /// 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)