This is my screens ....
I want to pass data from Offline View Controller to InstantVC. I don't know how to do that 🤔.
Basically, I have segmented Controller. When user tab Instant it show the segmented view controller and hide the Schedule view controller. And pass data according to selected segmented.
Here is the Offline View controller to pass data
switch response.result {
case .success:
if let result = response.data {
do {
let resultIs = try JSONDecoder().decode(GetActiveOrderModel.self, from:result)
print("Massage: \(resultIs.state)")
if let results = resultIs.orderData{
let storyboard = UIStoryboard(name: "Rider", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "instantVC") as! InstantVC
print(" Order ID is \(results.orderId)")
vc.arryOfOrder.append(results.orderId!)
//navigationController?.pushViewController(vc, animated: true)
}
} catch {
print(error)
}
}
case .failure(let error):
print(error)
}
And here is Instant view controller that restive data from Offline VC
var arryOfOrder = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
print("---------->>>>>>>>> \(arryOfOrder)")
}
// MARK: - Custom Functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arryOfOrder.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CellForInstantVC
cell.orderNum.text = "\(arryOfOrder[indexPath.row])"
return cell
}
func addOrderNumber(orderNumber : Int){
arryOfOrder.append(orderNumber)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
You can use prepare Segue to access Container controller and save its reference
class Master: UIViewController, ContainerToMaster {
#IBOutlet var containerView: UIView!
var containerViewController: Container?
#IBOutlet var labelMaster: UILabel!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "containerViewSegue" {
containerViewController = segue.destinationViewController as? Container
}
}
And then you can use containerViewController to pass data
containerViewController?.arryOfOrder = ArrayOfOrder
or you can have function in container ... pass ArrayOfOrder to that function .. which will also reload tableView
containerViewController?.updateData(dataArray: ArrayOfOrder)
If you want to pass data from parent to child on an action that happened in the parent class, you can access the children of the current UIViewController using
children.forEach { (viewController) in
if let temp = viewController as? InstantVC{
temp.property = dataToPass
}
}
The above will only work if both your view controllers are kept as children to the parent at all times and are never removed. If you remove them as children and re-add them at a later stage you will need to maintain references to the child and update that reference since the children array wont have that UIViewController. But since you are using storyboards, this should work fine.
If you want to access data from on action on the children class, you can access the parent view controller using:
let dataToUse = (parent as? OfflineVC).someProperty
Related
I have a viewController with a tableView, and another viewController that contains data that I'm trying to pass to the tableView. To add entries to the tableView I used segues, but the problem with segues is that they don't update the tableView permanently. They merely create an instance of the ViewController and add the entry there, but the original object remains unchanged. Both ViewControllers are part of a tab bar controller. What I want is to update the table permanently. Meaning, I want to be able to navigate to the viewController where the table is defined and see that's an entry has been added. Here's the code for the viewController with the tableView:
import UIKit
class FavoritesViewController: UIViewController {
public var shops = [
"hello world",
"hello world",
"hello world"
]
#IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
table.reloadData()
}
}
extension FavoritesViewController: UITableViewDelegate, UITableViewDataSource{
func add(_ shopName: String) {
print(shopName)
shops.append(shopName)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
cell.textLabel?.text = shops[indexPath.row]
return cell
}
// define the action. In this case "delete"
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
// do the actual deleting
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.beginUpdates()
shops.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}
}
And here's how I'm trying to update (in the case adding an entry) the tableView in the other viewController:
class MainViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate{
public var shopName:String?
// there are also many other vars, but they're irrelevant
public var favoritesDestinationVC = FavoritesViewController()
// prepares the data for the segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToFavs" {
favoritesDestinationVC = segue.destination as! FavoritesViewController
if let newShopName = shopName {
favoritesDestinationVC.shops.append(newShopName)
}
}
}
}
However, when I add the entry the to the table, the segue creates an instance of FavoritesViewController, adds that entry there, and then displays it in a popup window like this:
But when I dismiss this window the changes disappear (the tableView remains the same; 3 times "Hello World").
I want the changes to be saved in the tableView after dismissing this window. Any idea on how to do that? On how to make those changes permanent?
By your explanation, it looks like. Segue is defined as presenting FavoritesViewController modally. and this behavior is expected. By your implementation. Since you are not updating the view controller object which is part of the tab bar controller.
To make the changes in the controller in tab bar controller, Either you access that object using tabcontroller.viewcontrollers. Communicate using another way like a delegate or notification.
Edit:
It totally depends on where you want to access FavoritesViewController.
If you want to access from TabBarViewController (based on your view hierarchy it may change. be careful about index and typecasting):
let favVC = self.viewControllers?[1] as! FavoritesViewController
favVC.shops.append(newShopName)
If you want to access from a view controller which is part of same tab bar controller:
var favVC = self.tabBarController?.viewControllers?[1] as! FavoritesViewController
favVC.shops.append(newShopName)
Note: Viewcontrollers's index depends on viewcontroller order in your tab bar controller. And type casting depends upon your view hierarchy.
I have an app with three tabs as the root navigation, and there's a table view in the first tab. So when a user clicks on a table cell user should navigate to another View which contains two tabs. How do I achieve this?
Current Storyboard
This is what I have so far. I'm still learning ios development and I want to know if this is possible
Remove the storyboard segue from the table view to the second tab bar controller. And present the second tab bar controller from the table view controller's didSelectRowAt method. And you can pass data to the embedded view controllers like this
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let secondTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "SecondTabBarController") as? SecondTabBarController {
if let navControllers = secondTabBarController.viewControllers as? [UINavigationController] {
if let fourthVC = navControllers.first(where: { $0.topViewController is FourthVC })?.topViewController as? FourthVC {
fourthVC.name = "name"
}
if let fifthVCvc = navControllers.first(where: { $0.topViewController is FifthVC })?.topViewController as? FifthVC {
fifthVCvc.id = 20
}
}
self.present(secondTabBarController, animated: true, completion: nil)
}
}
Replace the class names and storyboard identifiers with proper class names and identifiers
class FourthVC: UIViewController {
var name: String?
override func viewDidLoad() {
super.viewDidLoad()
print(name)
}
}
class FifthVC: UIViewController {
var id: Int?
override func viewDidLoad() {
super.viewDidLoad()
print(id)
}
}
Yes you set any check for that in a single tab controller by this condition which tab you want to show reset from their.
When clicking on the row from the table view, you can use some code like this:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Segue to the other UITabBarController, pass selected information
let selectedCell = tableView.cellForRow(at: indexPath.row)
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "YourTabBarControllerIdentifier") as? YourTabBarController {
viewController.selectedIndex = 2 // or the index you want by default
viewController.modalTransitionStyle = .crossDissolve // or transition you want
self.present(viewController, animated: true, completion: nil)
}
}
i need an help, see this class
import UIKit
protocol TypesTableViewControllerDelegate: class {
func typesController(controller: TypesTableViewController, didSelectTypes types: [String])
}
class TypesTableViewController: UITableViewController {
let possibleTypesDictionary = ["bakery":"Bakery", "bar":"Bar", "cafe":"Cafe", "grocery_or_supermarket":"Supermarket", "restaurant":"Restaurant"]
var selectedTypes: [String]!
weak var delegate: TypesTableViewControllerDelegate!
var sortedKeys: [String] {
return possibleTypesDictionary.keys.sort()
}
// MARK: - Actions
#IBAction func donePressed(sender: AnyObject) {
delegate?.typesController(self, didSelectTypes: selectedTypes)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return possibleTypesDictionary.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TypeCell", forIndexPath: indexPath)
let key = sortedKeys[indexPath.row]
let type = possibleTypesDictionary[key]!
cell.textLabel?.text = type
cell.imageView?.image = UIImage(named: key)
cell.accessoryType = (selectedTypes!).contains(key) ? .Checkmark : .None
return cell
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let key = sortedKeys[indexPath.row]
if (selectedTypes!).contains(key) {
selectedTypes = selectedTypes.filter({$0 != key})
} else {
selectedTypes.append(key)
}
tableView.reloadData()
}
}
here the user can tap a cell of the tableView so that his prefer types are used on the next viewController for a search, now i need to build a class that do the same thing but there is no a tableview rather only 6 buttons in a view that the user can tap (so a viewController with only 6 different buttons to tap). The problem is that i don't know how to pass to the next viewController what buttons have been pressed and what are not, how can i build this class?
here is the function in the other class that need to know what buttons have been pressed
func fetchNearbyPlaces(coordinate: CLLocationCoordinate2D) {
mapView.clear()
dataProvider.fetchPlacesNearCoordinate(coordinate, radius:searchRadius, types: searchedTypes) { places in
for place: GooglePlace in places {
let marker = PlaceMarker(place: place)
marker.map = self.mapView
where is "types: serchedTypes"
What you wanna do is called delegation here is how you do it:
Make a protocol like this one:
protocol TransferProtocol : class
{
func transferData(types:[String])
}
Make the view controller with the buttons conform to that protocol, I like to do it by adding extensions to my classes like so:
extension ButtonsViewController:TransferProtocol{
func transferData(types:[String]){
//Do whatever you want here
}
}
Declare a variable in your Table View Controller class with the protocol you created as its type, this is called a delegate
weak var transferDelegate:TransferProtocol?
Before you segue to the Buttons View Controller you want to set that view controller as the delegate you just created like so:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? ButtonsViewController
transferDelegate = vc
vc?.transferData(types: selected)
}
If done correctly you should be able to work with the array you built in the Table View Controller(TypesTableViewController)
Im attempting to perform a segue from a table view cell that has one value "the floor number" to another vc which will be used to assign the number of rooms per floor. I have break points throughout the function to verify is the value that is passed is nil. The point is that it is not nil and it has the value "floor number". When i attempt to assign that value to a variable in the next VC i get the unwrapping optional found nil error. Could someone please help me out with this one as I don't see where this is coming from is the debugger shows me that I have a value inside the variable i want to pass. Code listing below. Thank you:
class AssignNumberOfRoomsForFloorsVC: UITableViewController {
//MARK: - Properties
private var managedObjectContext: NSManagedObjectContext!
private var storedFloors = [Floors]()
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
loadFloorData()
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func loadFloorData() {
let request: NSFetchRequest<Floors> = Floors.fetchRequest()
request.returnsObjectsAsFaults = false
do {
storedFloors = try managedObjectContext.fetch(request)
}
catch {
print("could not load data from core \(error.localizedDescription)")
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return storedFloors.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "floor cell", for: indexPath) as! FloorCell
let floorItem = storedFloors[indexPath.row]
cell.floorNumberTxt.text = String(floorItem.floorNumber)
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var selectedRow = self.tableView.indexPathForSelectedRow
let floorItem = storedFloors[(selectedRow?.row)!]
let destinationController = segue.destination
if let assignRoomsVC = destinationController as? DeclareRoomsVC {
if let identifier = segue.identifier {
switch identifier {
case "assign number of rooms":
assignRoomsVC.floorNumberTxt.text = String(floorItem.floorNumber) // ERROR HAPPENS ON THIS LINE
assignRoomsVC.selectedFloor = floorItem.floorNumber
default: break
}
}
}
}
}
In the prepare for segue method, the view hasn't loaded yet and thus your storyboard hasn't created any of your views.
It looks like floorNumberTxt is probably a text field or a label. You're trying to assign a property of this view, but that view doesn't exist yet. Thus the "found nil while unwrapping an Optional value” error message.
Try adding let _ = assignRoomsVC.view before assigning any of the view controller's view properties. By accessing the view (assignRoomsVC.view), you'll force the view load and instantiate all its subviews.
How is it possible to perform a segue from a UITabBarController Child ViewController to a DetailView of an UITableViewController with UINavigationController in between?
There is a TabBarController with two childs, FirstView(Most Viewed Symbol) and NavigationController(Contacts Symbol).
The FirstView has a button, which should perform a segue to Show Profile VC.
The NavCont has a TableView with subclass All ProfilesTVC with a prototype cell as child.
AllProfilesTVC has an array with three names which are displayed by the reused cell.
Which viewcontroller do I have to instantiate and prepare at the function prepareForSegue in FirstView (HomeVC) and where should the segue, which I create in storyboard, direct to? So that I'm at "John's" DetailView.
And is it possible that when I performed a segue to ShowProfileVC, that I can push the Back Button to return to the All ProfilesTVC?
There is a github repo for those who want to try at github repo
FirstView / HomeVC.swift
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// what do we do here ???
}
AllItemsTVC
class AllItemsTVC: UITableViewController {
let profiles = ["Joe", "John", "Ken"]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profiles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let profile = profiles[indexPath.row] as String
cell.textLabel?.text = profile
return cell
}
#IBAction func cancelFromShowProfile(segue: UIStoryboardSegue) {
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "ShowProfile":
if let showProfileVC = segue.destinationViewController as? ShowProfileVC {
// pass the data to the destinationVC
let selectedProfile = profiles[tableView.indexPathForSelectedRow()!.row] as String
showProfileVC.name = selectedProfile
}
default: break
}
}
}
ShowProfileVC
class ShowProfileVC: UIViewController {
#IBOutlet weak var textLabel: UILabel! {
didSet {
textLabel.text = name
}
}
var name = "Label"
override func viewDidLoad() {
super.viewDidLoad()
}
}
Thanks for any help.
You cannot do this with a segue, but that's not a problem because you can do it quite simply in code. Just give your view controllers an identifier in storyboard and instantiated them via this identifier with the appropriate UIStoryboard API.
Start by switching to the other tab bar item in code, and then first tell the navigation controller to popToRootViewController, after which you can push all the necessary controllers onto the navigation stack in turn. You can do all the configuration you normally do in prepareForSegue just before pushing the controllers.
The trick is to do it all with animated set to false except the last step.