Passing Data in Swift Between View Controllers in Same File - ios

Why can't I pass data from one view controller class to another view controller class when they are in the same .swift file?
I've done both of the tutorials linked bellow in an effort to understand passing data, and both have you make another .swift file for you second view controller. When I followed them exactly it works. When I do everything the same but just put the class SecondViewController in the same .swift file as the class FirstViewController it doesn't work. Why?
I'm building an application with three view controllers and I'd rather just keep all the code in one file if I can. Is this why it's not working or is it just bad form?
Tutorials:
How to Pass Data from View Controller (Swift : Xcode) on YouTube
Segue Between Swift View Controllers on CodingExplorer
This works:
// ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var TextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController: ViewTwo = segue.destinationViewController as ViewTwo
DestViewController.LabelText = TextField.text
}
}
// ViewTwo.swift
import UIKit
class ViewTwo: UIViewController {
#IBOutlet var Label: UILabel!
var LabelText = String()
override func viewDidLoad() {
Label.text = LabelText
}
}
This does not:
// ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet var TextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController: ViewTwo = segue.destinationViewController as ViewTwo
DestViewController.LabelText = TextField.text
}
}
class ViewTwo: UIViewController {
#IBOutlet var Label: UILabel!
var LabelText = String()
override func viewDidLoad() {
Label.text = LabelText
}
}

Working fine for me.
Have you set the classes for your views properly? The view with your textField (and probably a button to ViewTwo) should be set to ViewController and your second view with the label should be set to ViewTwo.
Check the connections between your label/textField. Are they properly connected to your class?
This is the code I used, which should be exactly the same:
import UIKit
class ViewController: UIViewController {
#IBOutlet var TextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController = segue.destinationViewController as! ViewTwo
DestViewController.LabelText = TextField.text
}
}
class ViewTwo: UIViewController {
#IBOutlet var Label: UILabel!
var LabelText = String()
override func viewDidLoad() {
Label.text = LabelText
}
}

Related

Why do I have to call my protocol functions two times to make it work?

I'm currently building a simple app to learn the protocol - delegate functionality. However my code doesn't work, even after I edited the way I did in my first practice app where it worked. In the FirstViewController there is a UILabel and a UIButton. When the user taps on the UIButton, a segue brings them to the SecondViewController where they should enter their name into a UITextField. After that, they can press the UIButton in the SecondViewController and the entered Name should be displayed in the UILabel in the FirstViewController.
I can't figure out why I have to call the protocol function two times in the #IBAction backButtonPresses(). Also, I can't figure out how to handle the same protocol function in the FirstViewController.
Here's the code for the FirstViewController.swift file:
import UIKit
class FirstViewController: UIViewController, SecondViewControllerDelegate {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var button: UIButton!
var labelText = ""
let secondVC = SecondViewController()
func changeLabelText(name: String) {
labelText = secondVC.enteredName
}
#IBAction func buttonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "goToSecondVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as? SecondViewController
destinationVC?.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = secondVC.enteredName
}
}
And here's the code of the secondViewController:
import UIKit
protocol SecondViewControllerDelegate {
func changeLabelText(name: String)
}
class SecondViewController: UIViewController, SecondViewControllerDelegate {
var delegate: SecondViewControllerDelegate?
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var backButton: UIButton!
var enteredName: String = ""
func changeLabelText(name: String) {
enteredName = name
}
#IBAction func backButtonPressed(_ sender: UIButton) {
changeLabelText(name: nameTextField.text ?? "")
delegate?.changeLabelText(name: nameTextField.text ?? "")
print("das ist der name \(enteredName)")
dismiss(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
You do not call any delegate method twice in backButtonPressed. You are calling two completely different changeLabelText methods. One is in SecondViewController, the other is on the delegate.
The call to changeLabelText in the SecondViewController is quite unnecessary. In fact, the enteredName property in SecondViewController is unnecessary. Also, SecondViewController should not be implementing its own delegate.
The call to changeLabelText on delegate is all you need. You just need to update the implementation of changeLabelText in FirstViewController to update the label's text with the new value.
func changeLabelText(name: String) {
nameLabel.text = name
}
Do not reference the secondVC property in FirstViewController. In fact, remove that property completely. It's not needed and it's referencing a completely different instance of SecondViewController than the one you actually present via segue.
I also suggest renaming the delegate method from changeLabelText to something more general such as enteredText. SecondViewController can be used by any other view controller to obtain some text. It's not specific to changing a label.
Here's your two view controllers with suggested changes:
class FirstViewController: UIViewController, SecondViewControllerDelegate {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var button: UIButton!
func enteredText(name: String) {
nameLabel.text = name
}
#IBAction func buttonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "goToSecondVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as? SecondViewController
destinationVC?.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
protocol SecondViewControllerDelegate {
func enteredText(name: String)
}
class SecondViewController: UIViewController {
var delegate: SecondViewControllerDelegate?
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var backButton: UIButton!
#IBAction func backButtonPressed(_ sender: UIButton) {
let name = nameTextField.text ?? ""
delegate?.changeLabelText(name: name)
print("das ist der name \(name)")
dismiss(animated: true)
}
}

Delegate data from one UIViewController to another one

I am completely new to Swift programming and tried to delegate a single String from one ViewController to another by clicking a send button. The problem is , that it does not work ...
I guess it would be easy for you to solve this and considering that it would be very helpful wether you explain me what I did wrong. :)
Thank you a lot
import UIKit
protocol protoTYdelegate {
func didSendMessage(message: String)
}
class New: UIViewController {
#IBOutlet weak var SendButton: UIButton!
var tydelegate: protoTYdelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func SendButtonAction(_ sender: Any) {
let nachricht = "It works fine."
tydelegate?.didSendMessage(message: nachricht)
}
}
import UIKit
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let controller = New()
controller.tydelegate = self
}
}
extension ThankYouPage: protoTYdelegate{
func didSendMessage(message: String) {
numbersView.text = message
}
As far as I understand, this code block doesn't work but the problem is not in the code, it's actually way that you choose to send data. In iOS development, there are many ways to send data. In your case, you need to use prepareForSegue method to send data to new class, not necessary to use delegates.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ThankYouPage") {
let vc = segue.destination as! ThankYouPage
vc.message = "Message that you want to send"
}
}
And you need to implement your ThankYouPage as:
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
var message = ""
override func viewDidLoad() {
super.viewDidLoad()
numbersView.text = message
}
}
In addition to that, you can use didSet method to print out the message to label instead of printing it directly in viewDidLoad method. Simply:
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
var message: String?{
didSet{
numbersView.text = message
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
I hope this helps you.
#Eyup Göymen's answer is right.
I have another way, assuming that you are not using segue and you are pushing to next controller by manual-code.
So your ThankYouPage code should be like :
import UIKit
class ThankYouPage: UIViewController {
#IBOutlet weak var numbersView: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func someButtonAction(_ sender: Any) { // By clicking on some, you are opening that `New` controller
let detailView = self.storyboard?.instantiateViewController(withIdentifier: "New") as! New
detailView.tydelegate = self
self.navigationController?.pushViewController(detailView, animated: true)
}
}
extension ThankYouPage: protoTYdelegate {
func didSendMessage(message: String) {
numbersView.text = message
}
}

Pass data from containerView to MainViewControler

I have this code:
MainViewControler:
class MainViewControler: UIViewController, ContainerToMaster {
#IBOutlet weak var systemContainerView: UIView!
#IBOutlet weak var favoriteProductBtn2: UIButton!
weak var containerViewController: Calculator1ViewController?
func changeBtn() {
favoriteProductBtn2.isHidden = true
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
}
}
CallculatorViewController:
#IBOutlet weak var containerView: UIView!
class CallculatorViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Calculator1ViewController:
protocol ContainerToMaster {
func changeBtn()
}
class Calculator1ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
containerToMaster?.changeBtn()
}
}
I have such an application layout:
Main view = MainViewControler.
In MainViewControler, I have a containerView (systemContainerView) in which the MainViewControler is located
In the CallculatorViewController, I have the next containerView in which the Calculator1ViewController is located.
When entering the Calculator1ViewController the function: containerToMaster?.changeBtn() should start (it should work in MainViewControler).
The problem is - this function does not work :(
Does anyone know how to fix it?
A contained viewController is embedded with an embed segue. You need to override prepare(for:sender) and set self as the containerToMaster delegate in the destination viewController. Your situation is complicated by the fact that you have a container view embedded in another container view, so you'll need to set up two delegates and pass the button call back:
protocol ContainerToMaster {
func changeBtn()
}
class MainViewControler: UIViewController, ContainerToMaster {
#IBOutlet weak var systemContainerView: UIView!
#IBOutlet weak var favoriteProductBtn2: UIButton!
weak var containerViewController: Calculator1ViewController?
func changeBtn() {
favoriteProductBtn2.isHidden = true
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVC = segue.destination as? CallculatorViewController {
destVC.containerToMaster = self
}
}
}
class CallculatorViewController: UIViewController, ContainerToMaster {
weak var containerToMaster: ContainerToMaster?
override func viewDidLoad() {
super.viewDidLoad()
}
func changeBtn() {
// pass the button call back
containerToMaster?.changeBtn()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVC = segue.destination as? Calculator1ViewController {
destVC.containerToMaster = self
}
}
}
class Calculator1ViewController: UIViewController {
weak var containerToMaster: ContainerToMaster?
override func viewDidLoad() {
super.viewDidLoad()
containerToMaster?.changeBtn()
}
}

prepareForSegue function not working

I am sure I have two view controllers, that have the appropriate files as their classes. (ViewController1.swift and ViewController2.swift) I am trying to pass data from one of the view controllers to the other one with the following code; but I get the error "UIView Controller is not convertible to ViewController2". What should I do? I tried to change as to as! and var to let; neither worked.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
if (segue.identifier == "btnSubmitSegue") {
var svc = segue.destinationViewController as ViewController2;
svc.DataPassed = textField.text
}
}
the code for ViewController2
import UIKit
class ViewController2: UIViewController {
var toPass: String = ""
#IBOutlet weak var labeld: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.labeld.text = "passed: \(self.toPass)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
the code for ViewController1
import UIKit
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var textField: UITextField!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TheSegue" {
let vc = segue.destinationViewController as! ViewController2
vc.toPass = self.textField.text!
}
}
}
The following example works fine for me. Code for the first view controller:
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TheSegue" {
let vc = segue.destinationViewController as! ViewController2
vc.passedText = self.textField.text!
}
}
}
And in the second view controller:
class ViewController2: UIViewController {
var passedText: String = ""
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.label.text = "passed: \(self.passedText)"
}
}
Don't forget to name the segue in the Storyboard:
Your destination view controller is referring to the wrong controller. You should have this in your code, not as! ViewController1:
let vc = segue.destinationViewController as! ViewController2
Also need to fix your IBOutlet name, the vc.toPass = self.textField.text! should be:
vc.toPass = self.labeld.text!
Make sure the custom class is set for the second view controller:
It may just be that ViewController2 is not declared as a subclass as UIViewController.
At the top of the ViewController2 file you would declare it as follows:
class ViewController2: UIViewController {
\\ ...
}
Have you set the name in the Storyboard ? Under custom class, Class needs to point to the view controllers associated class.
this class is not key value coding-compliant for the key
labelPassedData.' But I do not even have a variable like
labelPassedData
Click you view controller and press right hand arrow button, it shows all connections.
I guess you copy and pasted the view controllers and hence you get this problem.

I am trying to pass a string from one view controller to another view controller while unwinding using segues and I am not able to do so

It shows that the source view controler does not have the string variable so what should I do?
This is the code in my source view controller
#IBOutlet var textfield: UITextField!
#IBOutlet var tofirstbutton: UIButton!
#IBOutlet var tosecondbutton: UIButton!
var s:String!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "unwindtosecond"{
self.s=self.textfield.text
}
}
and this is the code in my destination view controller
#IBOutlet var textfield: UITextField!
#IBOutlet var tofirstbutton: UIButton!
#IBOutlet var tothirdbutton: UIButton!
#IBOutlet var label: UILabel!
#IBAction func unwindtosecond(Segue:UIStoryboardSegue){
if Segue.identifier == "unwindtosecond" {
var source:ViewController = Segue.sourceViewController as ViewController
var s:String = source.s!
}
I am getting an error saying that viewcontroller does not have a member named s.
Here is some example code to implement a main controller segueing to a second VC, and the second unwinding to the main controller. Notice that in the function the second cVC unwinds to, you can refer to the second controller and access a variable in the second controller. If you want to initialize a variable in the second VC from the main VC, you can use a prepareForSegue in the main VC.
import UIKit
class ViewController: UIViewController {
var varInMainVC = ""
#IBAction func segueToSecondVCAction(sender: UIButton) {
performSegueWithIdentifier("segueToSecondVC", sender: self)
}
#IBAction func unwindFromSecondVC(segue: UIStoryboardSegue) {
// return here from second VC
let vc = segue.sourceViewController as! SecondViewController
varInMainVC = vc.varInSecondVC
println("varInMainVC = \(varInMainVC)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class SecondViewController: UIViewController {
var varInSecondVC = ""
var varLoadedFromMainVC = 0
override func viewDidLoad() {
super.viewDidLoad()
varInSecondVC = "Test String to be returned"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Try these solutions:
Protocol delegate: https://stackoverflow.com/a/24299231/1925852
Setup a closure as a property: https://stackoverflow.com/a/24318588/1925852

Resources