Storyboard initialization and deinit - swift

When initializing a ViewController via a Storyboard (NS or UI), do you need to keep a reference to the storyboard or can you just ignore it when you are done with it and let it deinit?
class ViewController: NSViewController {
var secondarySB: NSStoryboard? = nil
#IBAction
func loadAndKeep(_ sender: NSButton) {
//keeping a reference
secondarySB = NSStoryboard.init(name: NSStoryboard.Name.init(rawValue: "Secondary"), bundle: nil)
let vc = secondarySB?.instantiateInitialController() as! Secondary
self.view.addSubview(vc.view)
}
#IBAction
func load(_ sender: NSButton) {
//ignoring the storyboard after I get the viewcontroller
let sb = NSStoryboard.init(name: NSStoryboard.Name.init(rawValue: "Secondary"), bundle: nil)
let vc = sb.instantiateInitialController() as! Secondary
self.view.addSubview(vc.view)
}
}

You do not need to keep a reference to the storyboard, but you do need to add the instantiated view controller as a child view controller.

Related

Swift NavigationController push method request doesn't work from PopUp view

The new PopUp ViewController is presented .overCurrentContext
There are 2 buttons with navigation for 2 other views from PopUp view.
A simple action such as print goes well, but when I try to segue programmatically (from xib file, popUpViewController) nothing happens.
let vc = RegisterEmailViewController.instantiate()
vc.coordinator = self
navigationController.pushViewController(vc, animated: false)
Goes well from any other view.
What could be wrong?
PopUpViewController code:
// Created by ᴀʟᴇxᴀɴᴅʀ ᴢʜᴇʟɪᴇᴢɴɪᴀᴋ on 23.12.2019.
// Copyright © 2019 ᴀʟᴇxᴀɴᴅʀ ᴢʜᴇʟɪᴇᴢɴɪᴀᴋ. All rights reserved.
import UIKit
class ViewController: UIViewController, Storyboarded {
weak var coordinator: MyCoordinator?
#IBAction func dismissPopUp(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
#IBAction func buttonEmail(_ sender: Any) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "EmailViewController") as? EmailViewController
self.navigationController?.pushViewController(vc!, animated: true)
}
#IBAction func buttonPhone(_ sender: Any) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PhoneViewController") as? PhoneViewController
self.navigationController?.pushViewController(vc!, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
There is MyCoordinator which inits all navigations and doesn't let me simply to segue/navigate by my own.
var childCoordinators = [Coordinator]()
var navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
Therefore, a reference to the controller solved the issue. It is possible to navigate aside, until new subViews, separate views are called.
Code that worked in this case:
let vc = RegisterEmailViewController.instantiate()
vc.coordinator = self
navigationController.pushViewController(vc, animated: false)
Conclusion. Simple there are two ways:
To delete all dependencies and other methods which use
UINavigationController
To declare only by new methods for global usage.

Prepare For Segue on return

So the code I am trying to implement in Swift is based upon this answer here for passing data back from a ViewController:
Passing Data with a Callback
Now my issue is after I have called:
self.navigationController?.popViewController(animated: true)
The Prepare For Segue function isn't called in my original View Controller. I assume it shouldn't be called anyway but from that answer I assume there is a possible way to do so?
First View Controller Snippets
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//ignore this segue identifier here, this function works when I am showing a new VC
if(segue.identifier == "certSegue"){
let certVC = segue.destination as! CertificateViewController
certVC.profileModel = profileModel
}
//this is what I need to be called
if(segue.identifier == "dpSegue"){
print("dpSegue")
let dpVC = segue.destination as! DatePickerViewController
dpVC.callback = { result in
print(result)
print("Data")
// do something with the result
}
//dpVC.dailyBudgetPassedThrough = "Test"
}
}
func showDatePicker(){
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "DatePickerVC") as? DatePickerViewController
self.navigationController?.pushViewController(vc!, animated: true)
}
Second View Controller
import UIKit
class DatePickerViewController: UIViewController {
var callback : ((String)->())?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func sendBackUpdate(){
print("Callback")
callback?("Test")
}
#IBAction func cancelButton(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
#IBAction func updateButton(_ sender: Any) {
sendBackUpdate()
self.navigationController?.popViewController(animated: true)
}
}
prepareForSegue is called if in Interface Builder a segue is connected
from a table/collection view cell to a destination view controller and the cell is tapped.
from a source view controller to a destination view controller and performSegue(withIdentifier:sender:) is called in the source view controller.
It's not called when a view controller is going to be presented with pushViewController
In your case assign the callback after instantiating the controller in showDatePicker, prepare(for segue is not needed.
func showDatePicker(){
let vc = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "DatePickerVC") as! DatePickerViewController
vc.callback = { result in
print(result)
print("Data")
// do something with the result
}
self.navigationController?.pushViewController(vc, animated: true)
}

Push UIViewController with Alert without UINavigationController

I have a button in UITableViewController. when I press this button, alert controller appears asks if the user wants to go to the cart page or stay in the same page, as follows,
if user?.uid != nil{
let title = "Item is added to your cart "
let alert = AlertController.instance(title: title)
present(alert, animated: true, completion: nil)
} else{
// Alert asks user to register..
}
AlertController is in different class and I created it with custom animation.
I want when user press (go to cart page) button, the cart page is displayed as if it was as (show,"push") segue.
This is how I pushed the view controller programmatically in alert controller class.
#IBAction func showCartButton(_ sender: Any) {
//---> go to cart page ...
print("cart button pressed")
//-----> this code is working fine with other UIviewcontrollers (however it is 'not working in UItableviewcontroller)
let storyBoard : UIStoryboard = UIStoryboard(name: "Cart", bundle:nil)
let CartViewController = storyBoard.instantiateViewController(withIdentifier: "CartPage")
navigationController?.pushViewController(CartViewController, animated: true)
//-----> this code shows the cart page without the navigation and tabs..
// let storyBoard : UIStoryboard = UIStoryboard(name: "Cart", bundle:nil)
// let CartViewController = storyBoard.instantiateViewController(withIdentifier: "CartPage")
// self.present(CartViewController, animated:true, completion:nil)
}
The push view controller is not working with Alert controller, I am not sure if it is because I used the navigation with the alert, and if so, is there a way I can push the view controller??
This is the whole AlertController Class I created in seperate storyboard and put it as initial view controller..
import UIKit
class AlertController: UIViewController{
#IBOutlet weak fileprivate var AddProductToCartLabel: UILabel!
#IBOutlet weak fileprivate var cartButton: UIButton!
#IBOutlet weak fileprivate var shoppingButton: UIButton!
#IBOutlet weak fileprivate var container: UIView!
var text = String()
override func viewDidLoad() {
setContainer()
setCartButton()
setShoppingButton()
}
override func viewDidLayoutSubviews() {
layoutContainer()
}
#IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func showCartButton(_ sender: Any) {
//---> go to cart page ...
print("cart button pressed")
let storyBoard : UIStoryboard = UIStoryboard(name: "Cart", bundle:nil)
let CartViewController = storyBoard.instantiateViewController(withIdentifier: "CartPage")
navigationController?.pushViewController(CartViewController, animated: true)
// let storyBoard : UIStoryboard = UIStoryboard(name: "Cart", bundle:nil)
// let CartViewController = storyBoard.instantiateViewController(withIdentifier: "CartPage")
// self.present(CartViewController, animated:true, completion:nil)
}
#IBAction func completeShopButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
fileprivate extension AlertController{
// to set the view above
func setContainer() {
let shape = CAShapeLayer()
shape.fillColor = UIColor.white.cgColor
container.backgroundColor = UIColor.clear
container.layer.insertSublayer(shape, at: 0)
}
func setCartButton(){
cartButton.clipsToBounds = true
//cartButton.layer.cornerRadius = 10
}
func setShoppingButton(){
shoppingButton.clipsToBounds = true
shoppingButton.layer.borderColor = UIColor.darkGray.cgColor
shoppingButton.layer.borderWidth = 1
//shoppingButton.layer.cornerRadius = 10
}
}
fileprivate extension AlertController{
// design the size of the container
func layoutContainer() {
let path = UIBezierPath(roundedRect: container.bounds, cornerRadius: 10)
let layer = container.layer.sublayers?.first as! CAShapeLayer
layer.path = path.cgPath
}
}
extension AlertController{
static func instance(title: String?) -> AlertController{
let storyboard = UIStoryboard(name: String(describing: self), bundle: Bundle(for: self))
let controller = storyboard.instantiateInitialViewController() as! AlertController
controller.text = title!
return controller
}
}
The problem is that when you try to push CartViewController, there is no navigation controller to push it on.
You present AlertController modally, and then try to do:
navigationController?.pushViewController(CartViewController, animated: true). If you put a breakpoint here and print out navigationController, I expect it is nil.
I suggest you have AlertController delegate back to your UITableViewController that is inside a navigation controller, and have the tableview controller push to the next screen. You could also present AlertController inside of a navigation view, but this seems unnecessary.

How do i load a viewcontroller from a xib file?

I tried to load a viewcontroller from a custom cell using delegates.But i get nil from the set delegate!
Here is a sample if anyone can help!
1. In Cell
protocol hotelFindDelegate{
func modalDidFinished(modalText: String)
}
class hotelFindCell: UITableViewCell {
var delegate:hotelFindDelegate?
#IBAction func findButton(sender: AnyObject) {
self.delegate!.modalDidFinished("HELLO")
print("Damn nothing works")
}
2. In Main View
class MainViewController:hotelFindDelegate {
let modalView = hotelFindCell()
override func viewDidLoad() {
super.viewDidLoad()
self.modalView?.delegate = self
}
func modalDidFinished(modalText: String){
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("HotelListVC") as UIViewController
self.presentViewController(viewController, animated: false, completion: nil)
self.modalView.delegate = self
print(modalText)
}
To load view controller from XIB do the following steps.
let settingVC : SettingsViewController = SettingsViewController(nibName :"SettingsViewController",bundle : nil)
later on you can push the same view controller object like
self.navigationController?.pushViewController(settingsVC, animated: true)
NSBundle.mainBundle().loadNibNamed("viewController", owner: self, options: nil)

What's wrong with my delegate?

I am new to swift and right now I am learning delegate. I think I already do the right things but it is still not working.
What I am doing was passing data from my ViewController to TestViewController
ViewController:
protocol viewControllerDelegate: class {
func viewcontrollerdelegate(setviewcontrollerdelegate: ViewController)
}
class ViewController: UIViewController ,UITextFieldDelegate {
weak var delegate: viewControllerDelegate?
#IBAction func nextViewandDelegate(sender: AnyObject) {
self.delegate?.viewcontrollerdelegate(self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showTestSegue" {
if let testViewController = segue.destinationViewController as? TestViewController {
testViewController.address = address.text!
testViewController.phone = phone.text!
}
}
}
}
TestViewController:
class TestViewController: UIViewController {
var name: String?
var address: String?
var phone: String?
var trydelegate: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC = storyboard.instantiateViewControllerWithIdentifier("viewcontroller") as! ViewController
VC.delegate = self
}
override func viewWillAppear(animated: Bool) {
addressLabel.text = address!
phoneLabel.text = phone!
trydelegateLabel.text = trydelegate //always nil here
}
}
extension TestViewController:viewControllerDelegate {
func viewcontrollerdelegate(setviewcontrollerdelegate: ViewController) {
self.trydelegate = setviewcontrollerdelegate.address.text!
}
}
I used segue to pass address and phone and they worked well.
But I am suck with delegate. Can anyone help me a little bit with it? I know the question is a little easy for you here.
Thank you very much.
In TestViewController in viewDidLoad you create new object vc which is not he same as the one which call prepareForSegue so that's why it doesn't work.
To fix this remove the code from viewDidLoad:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewcontroller") as! ViewController
vc.delegate = self
And in prepareForSegue add one line:
testViewController.phone = phone.text!
// New line
self.delegate = testViewController
That should help.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showTestSegue" {
if let testViewController = segue.destinationViewController as? TestViewController {
testViewController.address = address.text!
testViewController.phone = phone.text!
self.delegate = testViewController
self.delegate?.viewcontrollerdelegate(self)
}
}
}
remove #IBAction func nextViewandDelegate(sender: AnyObject) and change that prepareforsegue
I fixed it......it is working right now but I dont know why