Add a view controller as a subview in another view controller - ios

I have already read this LINK , but not working for me. I want to show a viewController as a subview in another viewController.
Here is my code -
import UIKit
import CarbonKit
class ViewController: UIViewController, CarbonTabSwipeNavigationDelegate {
#IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let items = ["All", "WOMEN", "MEN", "KIDS", "HOME", "CITY"]
let carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: items, delegate: self)
carbonTabSwipeNavigation.insert(intoRootViewController: self)
}
func carbonTabSwipeNavigation(_ carbonTabSwipeNavigation: CarbonTabSwipeNavigation, viewControllerAt index: UInt) -> UIViewController {
// let screen = self.storyboard?.instantiateViewController(withIdentifier: "demo") as! demo
// showSubViewContrller(subViewController: vc)
// return screen
let storyBoard = getStoryBoardByIndentifier(identifier: "All")
let vc = storyBoard.instantiateViewController(withIdentifier: "AllViewController") as! AllViewController
showSubViewContrller(subViewController: vc)
return vc
}
//Subview Controller
func showSubViewContrller(subViewController:UIViewController) {
self.addChildViewController(subViewController)
subViewController.view.frame = containerView.frame
self.containerView.addSubview(subViewController.view)
subViewController.didMove(toParentViewController: self)
}
func getStoryBoardByIndentifier(identifier:String)->UIStoryboard {
return UIStoryboard.init(name: identifier, bundle: nil)
}
}
I have a NavigationBar and a tapBar. Would like to show the viewController inside the view in a container.
But when the view loads it's coverUp/hide the tabBar.
How to solve this and show the viewController in my specified container.
Project Link - GitHub

Somehow i am able to fix your issue with below changes:
Replace this method carbonTabSwipeNavigation.insert(intoRootViewController: self) with carbonTabSwipeNavigation.insert(intoRootViewController: self, andTargetView: containerView) in viewDidLoad
Note : Give UITaBar bottom constraint to SuperView not SafeArea:
Add below code in ViewController:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tabbar.invalidateIntrinsicContentSize()
}
After doing this when you run you will UITabBar:

Related

coordinator is nil and not navigating to the next screen on button click

I have been trying to refactor my source code so that it would conform to the Coordinator Pattern. I have used UITabBarController as the parent viewController of my app which contains 4 viewControllers.
I have been following the tutorials on how to implement the Coordinator pattern for iOS apps, and I have created and set up the protocols and classes of the Coordinator. I have a button inside my viewController (child viewController of the TabbarViewController), however, on button click, coordinator is not pushing / navigating to the desired VC, and I see the coordinator is returning nil on the debug console while debugging through the breakpoint, and I could not figure it out how to resolve this issue.
MainCoordinator.swift:
class MainCoordinator: SubCoordinator {
var subCoordinators = [SubCoordinator]()
var navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func start() {
print("Initialized.. .")
UIApplication.app().window?.rootViewController = self.navigationController
let vc = SplashViewController.instantiate()
vc.coordinator = self
navigationController.pushViewController(vc, animated: false)
}
}
// testing using a simple Viewcontroller class, its background color is set to red, so if the
// navigation works, a blank red VC should appear. but not working so far
func testView() {
let vc = ViewController.instantiate()
vc.coordinator = self
navigationController.pushViewController(vc, animated: false)
}
}
SubCoordinator.swift:
protocol SubCoordinator {
var subCoordinators: [SubCoordinator] { get set }
var navigationController: UINavigationController { get set }
func start()
}
StoryBoarded.swift:
protocol StoryBoarded {
static func instantiate() -> Self
}
// I am using storyBoard, and `instantiate()` should instantiate and return the specified VC
// from the Storyboard with the specified VC id (?)
extension StoryBoarded where Self: UIViewController {
static func instantiate() -> Self {
let id = String(describing: self)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
return storyboard.instantiateViewController(withIdentifier: id) as! Self
}
}
FirstViewController.Swift:
class FirstViewController: UIViewController, StoryBoarded {
#IBOutlet weak var button: UIButton!
var coordinator: MainCoordinator?
//MARK: - viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
// If uncommented the below line, coordinator is not returning `nil`, but not navigating
anyways!
//coordinator = MainCoordinator(navigationController: UINavigationController())
}
#IBAction func onButtonTap(_ sender: Any) {
// So, basically I would expect the coordinator to navigate to the testView, but not
navigating
coordinator?.testView()
}
}
ViewController.swift:
// testView
class ViewController: UIViewController, StoryBoarded {
var coordinator: MainCoordinator?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = .red
}
}
and
// TabbarController, set as the root VC after the splashVC is completed
class MainViewController: UITabBarController, StoryBoarded {
var coordinator: MainCoordinator?
override func viewDidLoad() {
super.viewDidLoad()
let firstVC = UIStoryboard.firstViewController()
let secondVC = UIStoryboard.secondViewController()
let views: [UIViewController] = [firstVC, secondVC]
self.setViewControllers(views, animated: false)
self.navigationController?.navigationBar.isHidden = false
}
}
start() is being called, and splashVC appears and updates rootViewController with MainViewontroller on completion, But the navigation is not working at all on button click event.
Any feedback or help would highly be appreciated!
Since you're using the StoryBoarded protocol, you should follow the pattern and call instantiate() for initialization. Then, just set the coordinator.
class MainViewController: UITabBarController, StoryBoarded {
var coordinator: MainCoordinator?
override func viewDidLoad() {
super.viewDidLoad()
let firstVC = FirstViewController.instantiate()
let secondVC = SecondViewController.instantiate()
firstVC.coordinator = self.coordinator
secondVC.coordinator = self.coordinator
let views: [UIViewController] = [firstVC, secondVC]
self.setViewControllers(views, animated: false)
self.navigationController?.navigationBar.isHidden = false
}
}

ios Container View change View

I have a containerView added to a View Controller. I am hoping to on swipe of the containerView change the view in the container. However when I use the following in my swipe action function it adds the view to the whole page not just changing the view inside the container.
class SwipeDateViewController: UIViewController, UIGestureRecognizerDelegate {
#IBOutlet weak var swipeContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func swipeLeftHandler(_ sender: UISwipeGestureRecognizer) {
let viewController = self.storyboard!.instantiateViewController(withIdentifier: "swipeViewControllerStoryboard") as! SwipeViewController
self.swipeContainer.addSubview(viewController.view)
}
}
How do I just change the view in the container and not update the whole screen?
I think maybe you could add modify function in your custom vc.
Then just run function of it.
For example:
var customVC:EmbeddedViewController?
func addView() {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "EmbeddedViewController") as! EmbeddedViewController
self.addChild(vc)
vc.view.bounds = CGRect.init(x: 20, y: 40, width: 50, height: 60)
self.view.addSubview(vc.view)
vc.didMove(toParent: self)
customVC = vc
}
#IBAction func actionAddView(_ sender: Any) {
customVC?.changeColor(color: UIColor.black)
}
EmbeddedViewController
class EmbeddedViewController: UIViewController {
public func changeColor(color:UIColor) {
self.view.backgroundColor = color
}
}

I am trying to using a custom delegate in swift but when I want to call its methods, it did not get called

I have been searching for how the delegate works and I tried to do it in my project. Unfortunately, the delegate method I implement does not get called ever. I am trying to do a slide-out navigation panel. so what I did is that I put two uicontainerviews, one is for slide-out navigation panel and the other for main view controller
enter image description here
The code is that
For main view controller
protocol MainViewControllerDelegate {
func toggleSideMenu()
}
class MainViewController: UIViewController {
var delegate: MainViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Slide Action
#IBAction func slideMenuTapped(_ sender: UIBarButtonItem){
delegate?.toggleSideMenu()
print("Slide Menu has been tapped")
}
}
For container view controller
class ContainerVC: UIViewController {
#IBOutlet weak var SideMenuConstraint: NSLayoutConstraint!
#IBOutlet weak var slideMenuContainer: UIView!
#IBOutlet weak var mainViewContainer: UIView!
var mainViewController: MainViewController?
var isSideMenuOpened = false
override func viewDidLoad() {
super.viewDidLoad()
mainViewController = UIStoryboard.mainViewController()
mainViewController?.delegate = self
}
}
extension ContainerVC: MainViewControllerDelegate{
func toggleSideMenu() {
print("It works")
if isSideMenuOpened{
isSideMenuOpened = false
SideMenuConstraint.constant = -260
mainViewContainer.layer.shadowOpacity = 0
} else {
isSideMenuOpened = true
SideMenuConstraint.constant = 0
mainViewContainer.layer.shadowOpacity = 0.59
}
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
}
extension UIStoryboard{
static func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: Bundle.main) }
static func mainViewController() -> MainViewController? {
return mainStoryboard().instantiateViewController(withIdentifier: "MainViewController") as? MainViewController
}
}
Please let know what's wrong
I think the reason is that you embed your main view controller in navigation controller :
let navigationController = self.childViewControllers.last as! UINavigationController
let mainViewController = navigationController.topViewController as! MainViewController
mainViewController?.delegate = self
Here is where you got wrong:
mainViewController = UIStoryboard.mainViewController()
mainViewController?.delegate = self
this mainViewController is not the same as the child of the container view controller, so setting its delegate doesn't really do anything.
You need to first get the VC that is the child of the container view controller:
mainViewController = self.childViewControllers.last as! MainViewController
mainViewController.delegate = self

Unable to see controller added to UITabBar programmatically swift

I added 2 tabBar items from storyboard and one UITabBarItem - Menu programmatically. I am successfully able to open the controllers corresponding to tabBarItems which I created using storyboard. However, when I click on "Menu" a blank black screen appears,
#objc public class MainScreenTabsController : UITabBarController {
public override func viewDidLoad() {
super.viewDidLoad()
let tabController = MyViewController()
let tabBarItem = UITabBarItem(title: "Menu", image: UIImage(named: "more-options.png"), selectedImage: UIImage(named: "more-options"))
tabController.tabBarItem = tabBarItem
var array = self.viewControllers
array?.append(tabController)
self.viewControllers = array
}
public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return true;
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
I followed couple of tutorials for adding tab bar item but all of them had the code I wrote. Am I missing out something very basic?
EDIT:
Class for Menu Controller
#objc public class MyViewController:UIViewController {
public override func viewDidLoad() {
super.viewDidLoad()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
Your app is doing exactly what your code is telling it to do. You are creating an instance of MyViewController and adding it to the UITabBarController's array of View Controllers.
Your MyViewController class file simply defines a blank, black view.
I'm guessing you created a ViewController in your Storyboard that you want to use as MyViewController? If so, you need to instantiate that from the storyboard.
When you're editing your storyboard, assign the MyViewController class to the VC you want to use, and also give it a Storyboard ID - such as MyVC. Then, edit your viewDidLoad function to this:
public override func viewDidLoad() {
super.viewDidLoad()
// wrong way
// let tabController = MyViewController()
if let tabController = storyboard?.instantiateViewController(withIdentifier: "MyVC") as? MyViewController {
let tabBarItem = UITabBarItem(title: "Menu", image: UIImage(named: "more-options.png"), selectedImage: UIImage(named: "more-options"))
tabController.tabBarItem = tabBarItem
var array = self.viewControllers
array?.append(tabController)
self.viewControllers = array
}
}
Since you're creating the ViewController programatically ie. without nib/storyboard, you are responsible for instantiating a UIView object and setting the view property of the view controller. to do that implement the loadView method and assign the view object to view property of the viewController. then you can add custom views to the view object, check the code below.
class MyViewController: UIViewController {
override func loadView() {
// super.loadView() // DO NOT CALL SUPER
//create view
view = UIView()
view.backgroundColor = UIColor.white
//Add a custom view with red color
let customView = UIView()
customView.translatesAutoresizingMaskIntoConstraints = false
customView.backgroundColor = UIColor.red
view.addSubview(customView)
NSLayoutConstraint.activate(
[customView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
customView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
customView.topAnchor.constraint(equalTo: view.topAnchor),
customView.bottomAnchor.constraint(equalTo: view.bottomAnchor)]
)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
It would be good to use Storyboard/Nib for this purpose as you can easily configure custom views/controls using the autolayout in interface builder rather than doing it programmatically. :)
Edit:
if your'e using storyboard then instantiate view controller like given in below code
class MainScreenTabsController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let tabController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainViewController") as! MainViewController //if using storyboard
let icon = UITabBarItem(title: "Menu", UIImage(named: "more-options.png"), selectedImage: UIImage(named: "more-options")))
tabController.tabBarItem = icon
var controllers = self.viewControllers
controllers?.append(tabController)
self.setViewControllers(controllers!, animated: true)
}
}

swift subview does not full-fill parent view

When app starts, I use this method to set the root view controller.
func showRootViewController() {
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let mainViewController = sb.instantiateInitialViewController()!
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()
}
In main view controller, I've code to set the view to container view
class MainViewController: UIViewController {
#IBOutlet weak var headerView: UIView!
#IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if(userManager.hasRegistered()) {
let sb = UIStoryboard.init(name: "Login", bundle: nil)
self.setContentViewController(sb.instantiateInitialViewController()!)
} else {
let sb = UIStoryboard.init(name: "Registration", bundle: nil)
self.setContentViewController(sb.instantiateInitialViewController()!)
}
}
func setContentViewController(_ contentViewController: UIViewController) {
print(self.containerView.frame)
let contentView = contentViewController.view!
contentView.frame = self.containerView.bounds
self.containerView.addSubview(contentView)
}
}
Let look at the view, I have container view what is used to add subviews. I set the background to help everyone address the frame of container view
The subview is designed as below:
The result is not as my expected. ContainerView has gone somewhere (I really don't know), the subview is move on the top.
Please help me.
contentView frame is setted in the wrong position.
You should move this line of code:
contentView.frame = self.containerView.bounds
in
override func func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
contentView.frame = self.containerView.bounds
}
You cannot rely on dimensions in viewDidLoad.
Try viewDidLayoutSubviews instead. Be aware that it can be called multiple times
I have solved this type of issue.
i used a tableview with a single row(your subview)to wrap content

Resources