addChildViewController method is only for adding child viewControllers to containerViewController? - ios

I see the description of this method in Apple says
func addChildViewController(_ childController: UIViewController)
This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must call super in your implementation.
I see, so many examples that people use addChildViewController everywhere without containerViewController.
For example: I did not use containerView. I added like in the below? İt is correct?
// Create child VC
let childVC = UIViewController()
// Set child VC
self.addChildViewController(childVC)
// Add child VC's view to parent
self.view.addSubview(childVC.view)
// Register child VC
childVC.didMove(toParentViewController: self)
// Setup constraints for layout
childVC.view.translatesAutoresizingMaskIntoConstraints = false
childVC.view.topAnchor.constraint(equalTo: heroView.bottomAnchor).isActive = true
childVC.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
childVC.view.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
childVC.view.heightAnchor.constraint(equalToConstant: height).isActive = true

Like the documentation says, that method is intended to be used by view controllers that can contain another view controller. An example would be the navigation and tab bar controllers.
If you implemented a custom controller that, for example, put one controller on the top half on the screen and one on the bottom half, when you set the bottomHalfViewController property, you would call the addChildViewController method to let your controller know that it should handle that view controller as it's child.
This means that it will forward all view lifecycle calls like viewWillAppear:

Related

How to provide an argument to a view controller in containment?

I'm trying to pass an argument to a view controller in containment:
let childVC = ChildViewController()
addChild(childVC)
childVC.view.frame = frame
view.addSubview(childVC.view)
childVC.didMove(toParent: self)
ChildViewController has multiple properties, one of which has to be passed on from the parent view controller.
I've tried a few things, but none worked:
let childVC = ChildViewController(someProperty: someProperty)
or
let childVC = ChildViewController()
childVC.someProperty = someProperty
This line:
let childVC = ChildViewController()
Is almost always wrong. That will create an empty instance of ChildViewController with no views, outlets, or actions set up.
Generally you want to instantiate a view controller from a Storboard or a nibfile.
If you are asking how you install contents in a child view controller's views, the answer is "Don't do that."
If you want your parent view controller to have a child view controller, the easiest way to do that is to put a container view on the parent view controller in IB. Then control-drag from that container view onto the view controller you want to be a child, and when prompted, select "embed segue" as the type of link you want to create.
That will cause the system to install the child view controller in the container view and hook up all the plumbing to make it work
The parent view controller's prepare(for:sender:) method will be called right after the child view controller is instantiated, but before it's views are loaded. You can put code in your prepare(for:sender:) method to pass values to the child view controller (not set it's views directly, but set properties or call methods)

ViewDidAppear not called for child view added to rootViewController

I am trying to display a child view controller over the top of all elements on screen (including navigation bars), and the only way I've found that works is to add it as a child view controller to my window's rootViewController:
guard let window = UIApplication.shared.keyWindow,
let view = window.rootViewController?.view
else { return }
window.rootViewController?.addChildViewController(attachmentViewController)
view.addSubview(attachmentViewController.view)
attachmentViewController.view.snp.makeConstraints { make in
make.left.equalTo(view)
make.right.equalTo(view)
make.top.equalTo(view)
make.bottom.equalTo(view)
}
attachmentViewController.didMove(toParentViewController: window.rootViewController)
However, this doesn't call the viewDidAppear or viewWillDisappear methods... Why is that? I really need it to.
Instead of doing all that, simply present the view controller (don't push it as suggested).
let destination = SomeViewController.instantiateFromStoryboard(self.storyboard!)
present(destination, animated: true, completion: nil)
Focusing on the "why is that?" of your question.
When you call addChildViewController to a view you're not changing the "stack" of view controllers at all or the state of the host view controller; you're just adding a view controller as a child controller of the main view.
Usually when you work with child view controllers you orchestrate calls like willMove and didMove to trigger the view controller lifecycle behaviour.
In your case, you may be better off with a push or present. Present will give you the capability of overlaying a view controller.
As a note, I have used an approach similar to what you describe for managing sign in/out states adding either a signed in child view controller or a signed out view controller. In which case, when they change I usually call methods like:
// To add the child
addChildViewController(child)
view.addSubview(child.view)
child.didMove(toParentViewController: self)
// To remove the child.
child.willMove(toParentViewController: nil)
child.removeFromParentViewController()
child.view.removeFromSuperview()

How to hide child view from parent view after some delay

hide child view after few seconds
I set time for that but i cant access child viewcontroller in my timer function
I tried dissmiss , removefromparent about not worked.
only self.view.isHidden = true is worked
I can't place it in timer
My Parent view
Child View:
Button code:
Timer code:
In Like_btn_Action() function, you:
create an instance of LikeViewController
add it as a child view controller
add its view to your view
set that view's background color
and then the function exits. At this point, you no longer have a reference to your instance of LikeViewController ... likeVC has gone out of scope.
You need to use a class-level var to maintain the reference to the loaded child view controller, along these lines:
var likeVC: LikeViewController?
#IBAction func Like_btn_Action(_ sender: Any) {
likeVC = self.storyboard?.instantiateViewController( etc ...)
}
Then, when you want to remove the view you added, you can "get to it" via:
likeVC.view.removeFromSuperview()
for example.

Is it fine to nest a UIViewController within another without using addChildViewController?

I'm trying to make a custom ContainerViewController, but due to lots of difficulties with the ViewController transitions and making everything interactive, I've decided to mimic that functionality myself.
What I basically want to do, is have a paginated UIScrollView (the HeaderView) on the top control different another UIScrollView (the ControllersView) below that contains ViewControllers as pages so that as you swipe to a new page on the HeaderView, it also swipes to the next viewcontroller on the ControllersView. This is what the setup would look like.
My question is, is there anything wrong with having the aforementioned setup? All I'll do to add the view controllers to the ControllersView is just something like: controllersView.addSubview(pagecontroller1.view).
Some posts online seem to say that "the appropriate ViewController functions won't be called" or whatever. What do I seem to be missing here? I'm guessing there's a lot of dismissing and admitting of ViewControllers that I need to call every time a ViewController is out of frame right?
To clarify the question: Is it ok/efficient to do this? Should I be calling some viewWillAppear/disapper functions when the VC's get in and out of frame? If so, what should I call? I'm realizing that if I were to set things up this way, I need to manage a lot of things that are usually handled automatically, but as I mentioned before, custom ContainerViewControllers have failed me and I'm going with this.
PS. If you seem to still be lost on how this will look like, see my previous question here where I originally wanted to use a Container ViewController. There's a much better mockup there.
You can add and remove VC In Container Views
For - Is it ok/efficient to do this? Should I be calling some viewWillAppear/disapper functions when the VC's get in and out of frame? If so, what should I call?
As, We need to call WillAppear and Disappear Func when Adding and removing a VC , Thus Try using below Functions That will Handle these Responses
I use the Two specific Functions to add and remove Controller in ContainerView/UIView/SubView in ScrollView inside a UIView
To Add
private func add(asChildViewController viewController: UIViewController)
{
// Configure Child View
viewController.view.frame = CGRect(x: 0, y: 0, width: self.firstContainer.frame.size.width, height: self.firstContainer.frame.size.height)
// Add Child View Controller
addChildViewController(viewController)
viewController.view.translatesAutoresizingMaskIntoConstraints = true
// Add Child View as Subview
firstContainer.addSubview(viewController.view)
// Notify Child View Controller
viewController.didMove(toParentViewController: self)
}
To Remove
private func remove(asChildViewController viewController: UIViewController)
{
// Notify Child View Controller
viewController.willMove(toParentViewController: nil)
secondContainer.willRemoveSubview(viewController.view)
// Remove Child View From Superview
viewController.view.removeFromSuperview()
// Notify Child View Controller
viewController.removeFromParentViewController()
}
Creating Object
private lazy var FirstObject: firstVC =
{
// Instantiate View Controller
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "firstVC") as! firstVC
// Add View Controller as Child View Controller
self.addChildViewController(viewController)
return viewController
}()
For - controllersView.addSubview(pagecontroller1.view)
Answer - Yes Approbate func wont be called if pagecontroller1 is not loaded in to memory stack, to load that you need to notify pagecontroller1 that it is going to be added to memory stack as Child View , Just as We initiate a Controller and basically notifies the Controller to get its component loaded to memory stack to get some memory allocations
For Question - Is it fine to nest a UIViewController within another without using addChildViewController?
Check apple Documentation - https://developer.apple.com/documentation/uikit/uiviewcontroller/1621394-addchildviewcontroller
This is necessary just as to notify the controller who is going to be added in Another Parent View as Child
Sample Project
https://github.com/RockinGarg/Container_Views.git
Or
https://github.com/RockinGarg/ContainerView-TabBar.git
If Question is Still not answered Please Tell me what Func Exactly you want to handle by yourself

UISplitViewController: How to force showing the master ViewController

I am using a UISplitViewController, with the master and the detail viewcontrollers, without UINavigationControllers.
In some cases (for example when clicking on a universal link), I would like to force the app to always show the master viewcontroller.
How can I do that?
Is there a way to switch back from detail to master programmatically?
The split view controller is a beast, and the documentation is confusing. It is best understood by considering it as operating in two different modes: collapsed or not. Collapsed mode applies when the split view is presented in a horizontally compact view (i.e. iPhone), otherwise it is not collapsed (i.e. iPad).
The property preferredDisplayMode only applies if the view is NOT collapsed (i.e. iPad), and you can use this to select the master or detail view.
In collapsed mode, unless you are using navigation controllers, the original master view may be discarded:
After it has been collapsed, the split view controller reports having
only one child view controller in its viewControllers property. The
other view controller is collapsed into the other view controller’s
content with the help of the delegate object or discarded temporarily
But it is much better to use navigation controllers, as the split view controller is designed to work in conjunction with them:
The split view controller knows how to adjust the interface in more
intuitive ways. It even works with other container view controllers
(like navigation controllers) to present view controllers.
If you are using navigation controllers then the original master view may be at the bottom of the navigation stack:
In a horizontally compact environment, the split view controller acts
more like a navigation controller, displaying the primary view
controller initially and pushing or popping the secondary view
controller as needed
So you can do something like this:
if split.isCollapsed,
let nav = split.viewControllers[0] as? UINavigationController
{
nav.popToRootViewController(animated:false)
} else {
split.preferredDisplayMode = .allVisible
}
(It can get even more complicated if your master view pushes views in master as well as showing detail views. This code will pop to the root of the master view navigation stack)
You can set the preferredDisplayMode
self.splitViewController?.preferredDisplayMode = UISplitViewControllerDisplayMode.allVisible
Or if you are looking for something like a toggle action:
extension UISplitViewController {
func toggleMasterView() {
let barButtonItem = self.displayModeButtonItem
UIApplication.shared.sendAction(barButtonItem.action!, to: barButtonItem.target, from: nil, for: nil)
}
}
Usage:
self.splitViewController?.toggleMasterView()
You can define a custom UISplitViewController and assign it to your split view in storyboard:
import UIKit
class GlobalSplitViewController: UISplitViewController, UISplitViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
return true
}
}
My solution is to swap the position of your primary and secondary ViewControllers if user is using an iPad. Then set preferredDisplayMode = .primaryHidden. Example code below.
splitViewVieController = UISplitViewController()
let isIphone = UIDevice.current.userInterfaceIdiom == .phone
splitViewVieController.viewControllers = isIphone ? [primaryNavController, seconaryNavController] : [seconaryNavController, primaryNavController]
splitViewVieController.preferredDisplayMode = .primaryHidden
We can change the position or width of the primary ViewController if needed.
splitViewVieController.maximumPrimaryColumnWidth = splitViewVieController.view.bounds.width
splitViewVieController.preferredPrimaryColumnWidthFraction = 0.5
splitViewVieController.primaryEdge = .trailing

Resources