Swift - How to use pushViewController in NSObject - swift

I have a slide in/out side menu which is called when leftBarButtonItem in nab bar is tapped.
And I coded the slide menu with NSObject and I know NSObject doesn't have the pushViewController method.
navigationController?.pushViewController
I have a menu in UITableView in the NSObject and I want push viewController.
How can I make this work? Thank you.
import UIKit
class SlideMenuLauncher: NSObject, UITableViewDelegate,
UITableViewDataSource {
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationVC: UIViewController
switch indexPath.row {
case 0:
destinationVC = ControllerA()
case 1:
destinationVC = ControllerB()
default:
destinationVC = HomeController()
}
self.navigationController?.pushViewController(destinationVC, animated: false)
}
...

1.
You can make a #property of your parentVC in SlideMenuLauncher class.
var parentVC: UIViewController?
and then you can use this instead of self.
parentVC!.navigationController?.pushViewController(destinationVC, animated: false)
2.
You can post a notification instead of pushing from SlideMenuLauncher class and pass the destinationVC as object in notification. Observe this notification in your parentVC then fetch the destinationVC from notification object and push the controller.
3.
You can make a block or delegate of didSelectRowAt event.
Block Example:
/// Declare a block in `SideMenuLauncher`
typealias TableEventBlock = (_ controller: UIViewController) -> Void
var tableEventBlock: TableEventBlock?
/// In table did select method
if tableEventBlock != nil {
tableEventBlock!(destinationVC)
}
You need to define its call back in parentVC (You can define it anywhere, Do it in viewDidLoad:) and will have to use SideMenuLAuncher's instance.
sideMenuLauncherInstance.tableEventBlock = { controller in
self.navigationController?.pushViewController(controller, animated: false)
}

Related

How to dismiss UIViewController from UITableViewCell

I need to dismiss ViewController from the corresponding TableViewCell, but I'm getting an error message, "Value of type 'TableViewCell' has no member 'dismiss'"
self.dismiss(animated: true, completion: nil)
How can I dismiss the ViewController from the corresponding TableViewCell
If you just want the solution and don't really care about the structure of the application, the following will work. As the other guy mentioned, this probably isn't the best way to structure your application.
Make a delegate to the TableViewCell.
protocol TableViewDismissDelegate {
func dismissViewController()
}
class YourTableViewClass {
var delegate: TableViewDismissDelegate?
...
}
In your table view delegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = mainTableView.dequeueReusableCell(withIdentifier: YourTableViewClass.identifier, for: indexPath) as! YourTableViewClass
cell.delegate = self
return cell
}
Make sure your view controller conforms to your protocol:
extension YourViewController: TableViewDismissDelegate {
func dismissViewController() {
self.dismiss(animated: true, completion: nil)
}
}
You cannot say self.dismiss in a UITableViewCell, as dismiss is a UIViewController command, and a UITableViewCell is not a UIViewController.
What I like to do in this situation is get a reference to the UIViewController so that I can tell it to dismiss. To do so, I create a UIResponder extension, like this:
extension UIResponder {
func next<T:UIResponder>(ofType: T.Type) -> T? {
let r = self.next
if let r = r as? T ?? r?.next(ofType: T.self) {
return r
} else {
return nil
}
}
}
That extension just walks up the responder chain looking for an instance of any class we care to name. So now self.next(ofType: UIViewController.self) is the view controller, and we can tell it to dismiss.
(There are plenty of other solutions, but that's just a solution that I happen to like.)
It may be argued, however, that you should never have gotten yourself in this situation in the first place. It is no business of a UITableViewCell to be telling anyone to dismiss anything. This is a violation of model-view-controller principles. You should probably be looking at a completely different architecture here.

Unexpectedly found nil when sending data with Delegates and protocols pattern

I have 2 viewcontrollers, firstVC and secondVC. I want to send data from the first one to update the secondVC's variable and UI.
I want to send tableView's indexPath.row with delegate when it is tapped in didSelectRowAt.
This is what I try, but when selecting a row the app crashes with error:
Unexpectedly found nil while implicitly unwrapping an Optional value
I tried to debug and saw that the delegate is nil, even if I put a method to make the delegate firstVC.
SecondVC:
func setupDelegate() {
let FirstVC = storyboard?.instantiateViewController(identifier: "FirstVC") as! FirstVC
FirstVC.selectionDelegate = self
}
}
extension SecondVC: setSelectionDelegate {
//this is never executed
func didChoose(index: Int) {
lbl.text = String(index)
}
}
FirstVC:
protocol setSelectionDelegate {
func didChoose(index: Int)
}
var selectionDelegate: setSelectionDelegate!
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let secondVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "secondVC") as? secondVC
secondVC?.setupDelegate()
self.selectionDelegate.didChoose(index: indexPath.row)
}
Each time you call instantiateViewController explicitly, you get a new instance of the view controller and this is NOT the same instance that you are seeing in your device/simulator.
With storyboard segues ( embed or present modally... ) you have override prepare(...) function to get a reference to desired view controller instance.

De-initialzing a ViewController after dismissal?

I have two viewControllers in my App, the code for the first viewController is as illustrated below:
import UIKit
class firstViewController: UIViewController {
// The below two variables will be passed from the firstViewController to the secondViewController then back again from the secondViewController to the firstViewController:
var selectedRowValue: Int = 0
var selectedSectionValue: Int = 0
let main = UIStoryboard(name: "Main", bundle: nil)
lazy var secondViewController = main.instantiateViewController(withIdentifier: "secondViewController")
override func viewDidLoad() {
super.viewDidLoad()
}
// The below function will be triggered when the user tap on a specific tableView cell detailClosure icon. This is when the needed data get sent from this viewController to the secondViewController:
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let secondViewControllerProperties = secondViewController as! secondViewController
secondViewControllerProperties.receivedSelectedSectionValueFromFirstVc = indexPath.section
secondViewControllerProperties.receivedSelectedRowValueFromFirstVc = indexPath.row
// The below is the relevant content of a UILabel inside the tapped tableView cell by the user that get send to the secondViewController for it to be displayed as its NavigationBar title:
secondViewControllerProperties.selectedUniversalBeamSectionDesignation = arrayWithAllDataRelatedToUbsSections.filter({ $0.sectionSerialNumber == "\(arrayWithAllSectionsSerialNumbers[indexPath.section])" }).map({ $0.fullSectionDesignation })[indexPath.row]
self.present(secondViewControllerProperties, animated: true, completion: nil)
}
}
// The below extension inside the firstViewController is used to pass data back from the secondViewController to the firstViewController:
extension firstViewController: ProtocolToPassDataBackwardsFromSecondVcToFirstVc {
func dataToBePassedUsingProtocol(passedSelectedTableSectionNumberFromPreviousVc: Int, passedSelectedTableRowNumberFromPreviousVc: Int) {
self.selectedRowValue = passedSelectedTableRowNumberFromPreviousVc
self. selectedSectionValue = passedSelectedTableSectionNumberFromPreviousVc
}
}
Below is the code inside the second view controller:
import UIKit
class secondViewController: UIViewController {
weak var delegate: ProtocolToPassDataBackwardsFromSecondVcToFirstVc?
// The below variables get their values when the data get passed from the firstViewController to the secondViewController:
var receivedSelectedRowValueFromFirstVc: Int = 0
var receivedSelectedSectionValueFromFirstVc: Int = 0
var selectedUniversalBeamSectionDesignation: String = ""
// Inside the below navigationBar declaration, its labelTitleText will depend on the tapped tableViewCell by the user inside the firstViewController:
lazy var navigationBar = CustomUINavigationBar(navBarLeftButtonTarget: self, navBarLeftButtonSelector: #selector(navigationBarLeftButtonPressed(sender:)), labelTitleText: "UB \(selectedUniversalBeamSectionDesignation)", navBarDelegate: self)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(navigationBar)
}
// The below gets triggered when the user hit the back button inside the navigationBar of the secondViewController. This is where using the Protocol data get passed back to the firstViewController:
extension secondViewController: UINavigationBarDelegate {
#objc func navigationBarLeftButtonPressed(sender : UIButton) {
if delegate != nil {
delegate?.dataToBePassedUsingProtocol(passedSelectedTableSectionNumberFromPreviousVc: self.selectedTableSectionNumberFromPreviousViewController, passedSelectedTableRowNumberFromPreviousVc: self.selectedTableRowNumberFromPreviousViewController)
}
dismiss(animated: true) {}
}
}
However, what I am noticing is whenever the secondViewController gets dismissed when the user hit on the back button inside the navigationBar of the secondViewController. The secondViewController does not get de-initialized, and therefore, whenever I press on a different cell inside the tableView inside the firstViewController, the navigationBar title that gets displayed inside the secondViewController is still the same as the one displayed when I pressed the first time. Since the secondViewController did not get de-initialzied and thus, I am seeing the same values as the first time it got initialized.
My question is how to de-initialize the secondViewController when it gets dismissed, so that every time I tap on a different cell inside the tableView inside the firstViewController a new secondViewController gets initialized?
Your code generates secondViewController once and reuses it (it's a property).
lazy var secondViewController = main.instantiateViewController(withIdentifier: "secondViewController")
It means it will live until the first view controller is destroyed, and of course - will be reused.
Instead, you should create it as needed.
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
// Create the second view controller
let secondViewController = main.instantiateViewController(withIdentifier: "secondViewController")
let secondViewControllerProperties = secondViewController as! secondViewController
secondViewControllerProperties.receivedSelectedSectionValueFromFirstVc = indexPath.section
secondViewControllerProperties.receivedSelectedRowValueFromFirstVc = indexPath.row
// The below is the relevant content of a UILabel inside the tapped tableView cell by the user that get send to the secondViewController for it to be displayed as its NavigationBar title:
secondViewControllerProperties.selectedUniversalBeamSectionDesignation = arrayWithAllDataRelatedToUbsSections.filter({ $0.sectionSerialNumber == "\(arrayWithAllSectionsSerialNumbers[indexPath.section])" }).map({ $0.fullSectionDesignation })[indexPath.row]
self.present(secondViewControllerProperties, animated: true, completion: nil)
}
}
Remove the lazy var of course, it is no longer needed.
Also, you could just do:
let secondViewController = main.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController instead of casting it later, it's a bit cleaner.

pass data to previous view without segue,#IBaction swift

I have a View1 when i click on textbox i am going to view2(table view) to pick a value. I want to send the picked value to view1 for that textbox.
The controls are created programmatically so i am not using segue,IBActions.
I am trying to use the protocol methods still no success. Here is what i have tried.
class DynamicSuperView: UIViewController,UITableViewDelegate,UITableViewDataSource,dropdownDelegate,UITextFieldDelegate
{
func setValue(value:AnyObject)
{
print("dynamic view delegate method executed")
self.labelText = value as! String
//return selectedValue;
}
override func viewDidLoad() {
}
}
The second class is here with delegate method..
protocol dropdownDelegate {
func setValue(value: AnyObject);
}
class testClass: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate {
var delegate:dropdownDelegate! = nil
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vcName = names[indexPath.row]
print ("Table view cell clicked and value passed: \(vcName)")
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
self.navigationController?.popViewController(animated: true)
delegate.setValue(value: "Testing delegate")
}
}
Once i select the value in the tableview i am calling the delegate method and trying to pass that value but no success.
I don't want to create the new instance of the previous view controller because i will lose the data already entered by the user, so i am popping the current view controller and going to the previous view controller.
Please suggest if my approach i correct or not?
ERROR:
fatal error: unexpectedly found nil while unwrapping an Optional value
Thank you in advance
Try this:
view func ButtonPressed() {
print("Button Pressed!!") // This will create the new instance of the view controller.
let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "Storage") as! testClass
vc.delegate = self
self.navigationController?.pushViewController(vc, animated:true)
}
You are not setting the delegate to first view controller.

Passing values between ViewControllers based on list selection in Swift

I'm trying to pass the selected index number of a listView selection from one ViewController to another but am running into an issue with the tableView didSelectRowAtIndexPath delegate runs slightly later than the prepareForSegue function.
Basically, in didSelectRowAtIndexPath, I seta variable, which is then picked up in the prepareForSegue. The issue is that prepareForSegue seems to run the second that the cell is selected and before the didSelectRowAtIndexPath function is called so my variable is not passed.
My main bits of code are:
tableView didSelectRowAtIndexPath delegate, which sets 'selectedResult'...
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
selectedResult = indexPath.item
txtNameSearch.resignFirstResponder() //get rid of keyboard when table touched.
println("saved result")
//tableView.deselectRowAtIndexPath(indexPath, animated: false)
//var tappedItem: ToDoItem = self.toDoItems.objectAtIndex(indexPath.row) as ToDoItem
//tappedItem.completed = !tappedItem.completed
//tableView.reloadData()
}
prepareForSegue function which sends the variable as 'toPass' to the other ViewController ('detailViewController'):
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!){
if (segue.identifier == "detailSeque") {
println("preparing")
var svc = segue!.destinationViewController as detailViewController
svc.toPass = selectedResult
//println(tableView.indexPathsForSelectedRows().
//svc.toPass = tableView.indexPathForSelectedRow()
}
}
Thanks in advance
If you have an outlet to your tableView in your ViewController, you can just call indexPathForSelectedRow in prepareForSegue.
If your ViewController is a subclass of UITableViewController, then you can do:
let row = self.tableView.indexPathForSelectedRow().row
println("row \(row) was selected")
If your ViewController is not a subclass of UITableViewController, set up an IBOutlet to the UITableView in your view controller:
#IBOutlet var tableView: UITableView!
and wire that up in Interface Builder and call it from prepareForSegue as show above.
Instead of triggering your segue directly from a storyboard action, why don't you try programmatically calling performSegueWithIdentifier in your didSelectRowAtIndexPath method, after selectedResult is set?