Xcode Swift - Pass Button Path Data Between View Controllers - ios

My app has a category of things so when I press "Burger" button on my home viewcontroller it takes me to secondviewcontroller with more options (Buttons) like "spicy, mild, Fire". what I want to do is I want to save path of those button clicked on thirdviewcontroller as text.
For example on thirdviewcontroller a text says "Burger -> Spicy" or "Burger -> mind"
make sure I'm dealing with the button pressed in the path and not text entered.
How do I do that

One easy way is to keep two variables in the second and third view controller.
class FirstViewController : UIViewController {
#IBAction func buttonAction(_ sender: UIButton) {
let vc2 = ...// instantiate second view controller
vc2.textVal = sender.titleLabel!.text
//present vc2
}
}
Then in the second view controller get the text of the button and set it in a text
class SecondViewController : UIViewController {
var textVal: String?
#IBAction func buttonAction(_ sender: UIButton) {
let vc3 = ...// instantiate thrid view controller
let buttonText = sender.titleLabel!.text
vc3.textVal = "\(textVal) -> \(buttonText)"
//present vc3
}
}
Now in the third view controller set the label's text
class ThridViewController : UIViewController {
var textVal: String?
#IBOutlet weak var lblText: UILabel!
override func viewDidLoad() {
lblText.text = textVal
}
}
Hope it will help you.

Related

Swift Protocol Third VC to First VC

I need to pass a String and Array from my Third ViewController to my First ViewController directly using protocol/delegate, I have no problem doing it from VC 2 to VC 1 but I'm having a hard time with this. Also after clicking a button in my VC3 I need to go back to VC 1 and update the VC UI how would I do that? Would that have to be in viewdidload?
This in Swift UIKit and Storyboard
You need two protocols, and your firstVC and SecondVC have to conform those. When pushing new ViewController you need to give the delegate of that ViewController to self. On your third VC, when you click the button you need to call your delegate and pass your data to that delegate method, then repeat the same for other.
For FirstVC
protocol FirstProtocol: AnyObject {
func firstFunction(data: String)
}
class FirstVC: UIViewController, FirstProtocol {
weak var delegate: FirstProtocol?
#IBAction func buttonClicked(_ sender: Any) {
let secondVC = SecondVC()
secondVC.delegate = self
navigationController?.pushViewController(secondVC, animated: true)
}
func firstFunction(data: String) {
navigationController?.popToRootViewController(animated: true)
print(data)
}
}
You handle your navigation from your root. For better experience you can use something like coordinator pattern to handle it.
protocol SecondProtocol: AnyObject {
func secondFunction(data: String)
}
class SecondVC: UIViewController, SecondProtocol {
weak var delegate: FirstProtocol?
#objc func buttonClicked() {
let thirdVC = ThirdVC()
thirdVC.delegate = self
navigationController?.pushViewController(thirdVC, animated: true)
}
func secondFunction(data: String) {
delegate?.firstFunction(data: data)
}
}
Second VC is something that you just need to pass parameters.
class ThirdVC: UIViewController {
weak var delegate: SecondProtocol?
#objc func buttonClicked() {
delegate?.secondFunction(data: "data") // PASS YOUR ARRAY AND STRING HERE
}
}
What you need is unwind segue. Unwind segue will act like segue, only backward, popping, in this case, VC2. You can read here for more information.
Updating data code would be put in a function similar to prepareToSegue() but for unwind segue in your VC1.
Example of the function inside VC1:
#IBAction func unwindToDestination(_ unwindSegue: UIStoryboardSegue) {
switch unwindSegue.identifier {
case SegueIdentifier.yourSegueIdentifier:
let sourceVC = unwindSegue.source as! SourceVC
dataToPass = sourceVC.dataToPass
reloadData()
default:
break
}
}
Here is a different approach that accomplishes what you described by performing a Present Modally segue directly from View Controller 3 to View Controller 1, and sharing the string and array values by way of override func prepare(for segue....
In Main.storyboard, I set up 3 View Controllers, and have segues from 1 to 2, 2 to 3, and 3 to 1. These are Action Segues directly from the buttons on each VC, which is why you won't see self.performSegue used inside any of the View Controller files. Here is the picture:
In the first view controller, variables are initialized (with nil values) that will hold a String and an Array (of type Int in the example, but it could be anything):
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var updatableTextLabel: UILabel!
var string: String?
var array: [Int]?
override func viewDidLoad() {
super.viewDidLoad()
// These will only not be nil if we came here from the third view controller after pressing the "Update First VC" button there.
// The values of these variables are set within the third View Controller's .prepare(for segue ...) method.
// As the segue is performed directly from VC 3 to VC 1, the second view controller is not involved at all, and no unwinding of segues is necessary.
if string != nil {
updatableTextLabel.text = string
}
if let a = array {
updatableTextLabel.text? += "\n\n\(a)"
}
}
}
The second view controller doesn't do anything except separate the first and third view controllers, so I didn't include its code.
The third view controller assigns the new values of the string and array inside prepare (this won't be done unless you press the middle button first, to demonstrate both possible outcomes in VC 1). This is where your string and array get passed directly from 3 to 1 (skipping 2 entirely).
import UIKit
class ThirdViewController: UIViewController {
var theString = "abcdefg"
var theArray = [1, 2, 3]
var passValuesToFirstVC = false
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func updateFirstVC(_ sender: UIButton) {
passValuesToFirstVC = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if passValuesToFirstVC && segue.identifier == "toFirst" {
// Cast segue.destination (which on its own has type UIViewController, the superclass to all your custom View Controllers) to the specific subclass that your first View Controller belongs to
let destinationVC = segue.destination as! FirstViewController
// When your first view controller loads, it will receive these values for the 'string' and 'array' variables. They replace the original 'nil' values these had in the FirstViewController definition.
destinationVC.string = theString
destinationVC.array = theArray
}
}
}
Note that there is an IBOutlet to the label on the first View Controller which contains the text to be updated.
After visiting the third view controller, pressing the "Update First VC Text" button, and then performing the segue back to the first, here is how it will look:
This doesn't address the part about protocols and delegates in your question (as I'm not sure how they're being used in your program, and other answers have already addressed that), but it illustrates the method of transferring variables directly from one View Controller to another without unwinding segues or using the UINavigationController.

Pass data between ViewController without Segues

I am pretty new to swift development and have some problems understanding how to pass data between ViewController.
I want to build a simple music player app which has three views (Player, Playlists, Tracks).
At start the Player is shown to the user. From there the user can press a button and the Playlists view come up. Now he can select a playlist and the next view Tracks is displayed.
If he press on a track he gets back to the Player view and the track is playing. So I need to pass my track to my PlayerViewController.
Currently I'm using Segues to display each ViewController.
Player -> Playlists -> Tracks -> Player
But this will initialise the Player again which means that values/variables get reset. How can I avoid this?
If you are getting from view controller B to view controller C by saying present, then view controller C can speak to view controller B as its presentingViewController.
Try using Unwind segues to pass data i guess they can help you out.
An unwind segue (sometimes called exit segue) can be used to navigate
back through push, modal or popover segues (as if you popped the navigation
item from the navigation bar, closed the popover or dismissed the modally
presented view controller). On top of that you can actually unwind through
not only one but a series of push/modal/popover segues, e.g. "go back"multiple steps in your navigation hierarchy with a single unwind action.When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.
//ViewControllerA:
import UIKit
class ViewControllerA: UIViewController {
var dataRecieved: String? {
willSet {
labelOutlet.text = newValue
}
}
#IBOutlet weak var labelOutlet:UILabel!
#IBOutlet weak var nextButtonOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func nextButtonAction(_ sender:UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerB") as! ViewControllerB
controller.dataPassed = labelOutlet.text
self.present(controller, animated: true, completion: nil)
}
// segue ViewControllerB -> ViewControllerA
#IBAction func unwindToThisView(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ViewControllerB {
dataRecieved = sourceViewController.dataPassed
}
}
}
//ViewControllerB
import UIKit
class ViewControllerB: UIViewController , UITextFieldDelegate{
#IBOutlet weak var textFieldOutlet: UITextField!
var dataPassed : String?
override func viewDidLoad() {
super.viewDidLoad()
textFieldOutlet.text = dataPassed
textFieldOutlet.delegate = self
}
// UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// User finished typing (hit return): hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
dataPassed = textField.text
}
}
//From the Return Button click control and drag to exit of the viewcontrollerB as show in the image.
To pass data between View Controllers, have this block in your code:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let feed = segue.destination as! SecondViewControllerName
feed.variableinsecondviewcontroller = variableincurrentviewcontroller
}
If that didn't help, you might need to elaborate on what exactly you want with your code...
Use struct class and access your object any where using the stuct object
Like this
struct SomeStruct { var name: String init(name: String) { self.name = name } } var aStruct = SomeStruct(name: "Bob") var bStruct = aStruct // aStruct and bStruct are two structs with the same value! bStruct.name = "Sue" println(aStruct.name) // "Bob" println(bStruct.name) // "Sue"

Xcode 8/Swift 3: how to make ViewController save state when segue occurs?

App has two View Controllers: ViewController (this is the main View Controller that displays the majority of the app's content) and SecondViewController (accessible via a UIButton on ViewController; SecondViewController is only used to display a user's inventory, and a UIButton within SecondViewController allows the user to return to the original view, ViewController). Currently, the app uses the "Show" action segue to switch between View Controllers when the user presses the appropriate UIButton. However, after switching from ViewController to SecondViewController, and then pressing the UIButton to return to ViewController, the properties of ViewController have been reverted to the properties that occur when the app launches (background color is changed, certain text fields appear that shouldn't).
So, how do I "save the state" of ViewController when the user moves to SecondViewController, so that the user resumes where they left off when they return to ViewController?
What you are looking for is an unwind segue. Here's the simplest way of how to create it:
In your ViewController (or, basically any other view controller you are willing to pop to) create an IBAction that accepts an instance of a segue (function name doesn't really matter):
#IBAction func unwindToThisVC(segue: UIStoryboardSegue) { }
In the storyboard, go to SecondViewController, and control + drag from your UIButton to the Exit outlet of ViewController and then select the IBAction you've created in step 1:
More on Unwind Segues
The way you are doing it now (using Show from the second to get back to the first) actually brings up a third VC.
What you want to do is dismiss the second view controller.
The normal way is to implement a protocol for the second one that the first one implements and then to have a function in that protocol for the second one to let the first one know it is done.
When the function is called, the first one dismisses the second and then it will be shown again with its state intact.
Here is a simple example of segue and unwind that you can adapt to your problem... Assume that you have ViewController with label and a button and a SecondViewController with label and a button.
For the first ViewController...
import UIKit
//steps to receive data back from SecondViewController...
//1. create protocol in the SecondViewController (see SecondViewController code)
//2. conform to the protocol
class ViewController: UIViewController, UnwindSegue {
//3. method that gets triggred.
func dataReceived(dataSegued: String) {
labelOne.text = dataSegued
}
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var labelOne: UILabel!
var textReceived : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func btPressed(_ sender: Any) {
performSegue(withIdentifier: "goToSecondController", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToSecondController" {
let destinationVC = segue.destination as! SecondViewController
destinationVC.textSegued = textField.text!
//4. create delegate in the SecondViewController (see SecondViewController code)
//5. set ourselves up as delegate of SecondViewController
destinationVC.delegate = self
//6. then dismiss the SecondViewController (see SecondViewController code)
}
}
}
Then for your SecondViewController...
import UIKit
//1. create protocols and delegates to transfer data back
protocol UnwindSegue {
//single required method with a single parameter
func dataReceived(data:String)
}
class SecondViewController: UIViewController {
var textSegued : String?
//4. create delegate of the protocol of type CanReceive that can be a nil. If it is nil, it doesn't go anywhere when BT is pressed
var delegate : UnwindSegue?
#IBOutlet weak var label: UILabel!
#IBOutlet weak var secondTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
label.text = textSegued
}
#IBAction func btTwoPressed(_ sender: Any) {
//this is not triggered if var delegate is nil (as defined as optional)
delegate?.dataReceived(data: secondTextField.text!)
//6. dismiss the 2nd VC so you can see the fist VC
dismiss(animated: true, completion: nil)
}
}

Passing data from Pop-over ViewController UITextfield back to Master ViewController

I have an app setup to have a Master root viewController with a Navigation bar that has a "Settings button". When the user taps the settings button, it brings up a 'settingsTableViewController' that is not dynamic, but rather static so i can format the tableviews with settings like style.
in this settings view, i have a UITextField that takes a Person's name.
When the user clicks "Done" in the navigation bar, i want to pass that name back to the Master Root ViewController so i can use it in the title to display the Person's name. (I want to pass the name upon dismissing the view)
I have tried to use segue's but no luck. Here is a bit of what i tried.
SettingsViewController (pop's over the MasterVC)
class SettingsTableViewController: UITableViewController {
#IBOutlet weak var nameTextfield: UITextField!
#IBAction func done(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override viewDidLoad(){
self.title = "Settings"
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Trying to pass what was typed in the textfield to the Root ViewController and store this name in a variable of type String called 'name'
if segue.identifier == "masterView"{
let masterViewController = segue.destinationViewController as! MasterTableViewController
masterViewController.name = nameTextField.text
print("Segue was used")
}
}
}
MasterTableViewController.swift
class MasterTableViewController: UITableViewController {
var name: String!
// I am trying to then display the name entered in the pop-over view in this root view controller's title
override viewDidLoad(){
self.title = name!
}
}
My question is, what did i do wrong? I have tried to use delegation but i get nil and the data doesn't seem to get passed either way so any leads will greatly help. Thanks
There is a different kind of segue called Unwind Segue to do that. It doesn't create a new mvc and its used to pass data back to the vc that presented the current one. here is how to do it
First, go to your storyboard and control drag from settingVc to the exit button on top of it (to itself). it will give you 'Selection Segue' and choose IBAction goBack. This means any vc that presented the current one will get to prepare if they implement this method. In other words, you're putting out a protocol and the presenter vc will conform by implementing goBack IBAction. here is how to implement that. In your Mater vc
//You must have this function before you do the segue in storyboard
#IBAction func goBack(segue: UIStoryboardSegue){
/* this is optional
if let stv = segue.sourceViewController as? SettingsTableViewController{
self.name = stv.nameTextfield?.text
}
*/
}
In your setting vc (current vc)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//make sure you set the id of your segue to "Your Go back Unwind segue". ofc u can name it whatever
if segue.identifier == "Your Go back Unwind segue"{
if let mtvc = segue.destinationViewController as? MasterTableViewController{
mtvc.name = nameTextField.text
print("Segue was used")
}
}
}
and done method should be something like this
#IBAction func doneEditing(sender: UIButton) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}

passing data from one tab controller to another in swift

My application has three viewController associated with three tab of tabBar. I want to switch from 1st tab to 3rd tab and pass some data from 1st view controller to 3rd view controller. I can't do it with segue, because segue create navigation within the selected tab. That is not my requirement. I want to switch tab in tabBar and pass some data without any navigation. How can i do it ?
Swift 3 in latest Xcode version 8.3.3
First you can set a tab bar delegate UITabBarControllerDelegate in FirstViewController. You can use this when you want to send data from one view controller to another by clicking the tab bar button in UITabBarViewController.
class FirstViewController: UIViewController ,UITabBarControllerDelegate {
let arrayName = ["First", "Second", "Third"] 
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController.isKind(of: FirstsubsecoundViewController.self as AnyClass) {
let viewController = tabBarController.viewControllers?[1] as! SecondViewController
viewController.arrayData = self.arrayName
} 
return true
}
}
Get data in SecondViewController:
class SecondViewController: UIViewController {
var arrayData: [String] = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
print(arrayData) // Output: ["First", "Second", "Third"]
}
}
you can use this code : Objective C
[tab setSelectedIndex:2];
save your array in NSUserDefaults like this:
[[NSUserDefaults standardUserDefaults]setObject:yourArray forKey:#"YourKey"];
and get data from another view using NSUserDefaults like this :
NSMutableArray *array=[[NSUserDefaults standardUserDefaults]objectForKey:#"YourKey"];
swift
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toTabController" {
var tabBarC : UITabBarController = segue.destinationViewController as UITabBarController
var desView: CaseViewController = tabBarC.viewControllers?.first as CaseViewController
var caseIndex = overviewTableView!.indexPathForSelectedRow()!.row
var selectedCase = self.cases[caseIndex]
desView.caseitem = selectedCase
}
}
Okay, i tried with creating a singleton object in viewController of first tab and then get that object's value from viewController of third tabBar. It works only for once when third tab's view controller instantiates for the 1st time. I never got that singleton object's value in third tab's view controller except the first time. What can i do now ? In my code - In first tab's controller, if i click a button tab will be switched to third tab. Below is my code portion -
In First tab's controller -
#IBAction func sendBtnListener(sender: AnyObject) {
Singleton.sharedInstance.brandName = self.searchDisplayController!.searchBar.text
self.tabBarController!.selectedIndex = 2
}
In Third tab's Controller -
override func viewDidLoad() {
super.viewDidLoad()
//Nothing is printed out for this portion of code except the first time
if !Singleton.sharedInstance.brandName.isEmpty{
println(Singleton.sharedInstance.brandName)
}else{
println("Empty")
}
}
In Singleton Object's class -
class Singleton {
var name : String = ""
class var sharedInstance : Singleton {
struct Static {
static let instance : Singleton = Singleton()
}
return Static.instance
}
var brandName : String {
get{
return self.name
}
set {
self.name = newValue
}
}
}
Edited :
Okay at last it's working. For others who just want like me, please replace all the code from viewDidLoad() to viewWillAppear() method in third tab's (destination tab) controller and it will work. Thanks.

Resources