I am developing an IOS Application. I have added the UIViewController
in View Pager. I want to reinitialize it when the language is changed. Here I want to remove all child UIViewController
from UIViewPager
and again back to add all UIViewController
into Viewpager. How can I do that?
Sample Code
let viewPager = ViewPagerController()
viewPager.options = options
viewPager.dataSource = self
viewPager.delegate = self
self.addChildViewController(viewPager)
Swift 3.1
xcode 8.3.3
To delete the View Controller from the storyboard, select the View Controller by clicking the Show Document Outline icon and then clicking on View Controller Scene in the Document Outline. Then press Backspace or choose Edit > Delete.
After the long search to remove the view controllers from viewpager. I did it in the following way.
if self.childViewControllers.count > 0{ let viewControllers:[UIViewController] = self.childViewControllers for viewContoller in viewControllers{ viewContoller.willMove(toParentViewController: nil) viewContoller.view.removeFromSuperview() viewContoller.removeFromParentViewController() } }
here self is , Current UIViewController which has View Pager. I need to remove all the childview controllers from the view pager. So, i get the list of view controllers from Current UIViewController. Then i removed it from the Parent view.
For swift 4.2
if self.children.count > 0{ let viewControllers:[UIViewController] = self.children for viewContoller in viewControllers{ viewContoller.willMove(toParent: nil) viewContoller.view.removeFromSuperview() viewContoller.removeFromParent() } }
EDIT
Remove top childview controller:
func removeTopChildViewController(){ if self.children.count > 0{ let viewControllers:[UIViewController] = self.children viewControllers.last?.willMove(toParent: nil) viewControllers.last?.removeFromParent() viewControllers.last?.view.removeFromSuperview() } }
childViewControllers.forEach({ $0.willMove(toParentViewController: nil) $0.view.removeFromSuperview() $0.removeFromParentViewController() })
This answer is for swift 4.2 and above one is less than 4.2 versions.
children.forEach({ $0.willMove(toParent: nil) $0.view.removeFromSuperview() $0.removeFromParent() })
Here is the more concise version for removing all child controllers from the parent. You can use self.childViewControllers to define explicitly. As this approach, you can get rid of these extra conditions to check.
Swift 4.2 and above
create extension
on UIViewController
and add removeChild()
method
extension UIViewController {
func removeChild() {
self.children.forEach {
$0.willMove(toParent: nil)
$0.view.removeFromSuperview()
$0.removeFromParent()
}
}
}
Usage:
call removeChild
from parent UIViewController
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.removeChild()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With