Call a textfield from other view controller in swift (prepareforsegue) - swift

I read a lot of posts and videos of this and I read that is with a function calls "prepareforsegue" but I don´t understand where to implement and what other things do I have to do. I have 4 textfields that I want to call from another later controller. Thank you very much for the answer. :)

You can't set values or access to textfields or any other outlet inside prepareforsegue method. That because prepareforsegue method is called "before" the destination controller's outlets get set. So you need to create a variable in your destination controller that receives the value for the textfield and then in viewDidLoad in destination controller set it to the textfield.
In prepareforsegue method :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destinationViewController = segue.destinationViewController as? SecondViewController {
destinationViewController.valueForTextField = "Hi"
}
}
In the destination controller (which is SecondViewController in my case) :
#IBOutlet weak var textField: UITextField!
var valueForTextField: String?
override func viewDidLoad() {
super.viewDidLoad()
textField.text = valueForTextField
}

It helps to post your code.
Inside prepareForSegue, grab the destination ViewController that holds your textFields by using:
let vc = segue.destinationViewController
then vc.textField1.text = "Your Text here" & repeat for your other text fields.

Related

Show Label Value on 2nd View - Swift

Since i'm new and a newbie on Swift can someone tell me how I can get the label value on screen 1 to show on screen 2. Thanks
Edit: So I tried the way you told me but for some reason the Label text did not change in View 2. Any help? Thanks
I am passing textFiled data to destViewController to show how segue performs when passing data.
Note: If you want to pass string data to your destVC.You can assign your string like var someValue: String
mainStoryBoard:
MainVC:
#IBOutlet weak var textField: UITextField!
//or you can assign string like var someValue: : String
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let viewController = segue.destination as! destVC
viewController.dataText = textField.text // someValue.text
}
DestVC:
#IBOutlet var label: UILabel!
var dataText = String()
override func viewDidLoad()
label.text = dataText
}
Output:
You already have a segue between ViewController1 and ViewController2 it seems, so now you just need to pass some date from one to another. This can be done in the function prepare(for segue: UIStoryboardSegue, sender: AnyObject?) which is called when you transition from ViewController1 to ViewController2.
The UIStoryboardSegue class has a property called source of type UIViewController and another property called destination which is also a UIViewController.
So, if you define a property on your ViewController2, like so:
var labelValue: String
Then you can pass a value to it in your prepareForSegue defined on ViewController1 like so:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let viewController2 = segue.destination as? YourViewController2 else {
return
}
viewController2.labelValue = theValueFromViewController1
}
Here is tutorial telling you a bit more (in Objective C though)
And this is also a fine introduction.
Hope that helps you.
I'll consider you have ViewController class VC1 (screen 1) & ViewController class VC2 (screen 2). I see from the screenshot that, you're already using a segue to go from the VC1 to VC2 view.
Now, declare a variable in your VC2 class let's call it labelValue,
class VC2 {
var labelValue: String?
...
}
Whenever you use a storyboard segue to move from one viewcontroller's view to other viewcontroller's view a method named,
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
will get called if it's overriden in the source viewController class (scene1 in your case). In this method you'd be able to access the destination view controller (scene 2) and it's properties. So for your case you can implement it like this,
class VC1 {
//I have assumed the below label will hold the value which you want to pass it to the scene 2.
var lblResult: UILabel!
......
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// You can access the VC2 instance from the segue
if let vc2 = segue.destinationViewController as? VC2 {
vc2.labelValue = lblResult.text
}
}
Now once you implement the prepareForSegue: method correctly as shown above, you'd be able to get the label's value from scene 1 to labelValue property of scene2.
Do learn more about segues here : More About Segues and Storyboards here.
================================
Edit:
Coming to your edited question, in your View2 viewController, you've declared labelNumber1 as String and not as UILabel, so whenever you pass the value to labelNumber1, the value will be containing in this variable and it will not be shown in the screen since it is just a normal string. So what you can do is, declare the labelNumber1 as UILabel
class View2: UIViewController {
#IBOutlet var labelNumber1: UILabel!
.....
}
and in your prepare for segue in ViewController1 make the following change,
class ViewController1: UIViewController {
.....
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// You can access the VC2 instance from the segue
if let view2 = segue.destinationViewController as? VC2 {
view2.labelNumber1.text = lblResult.text
}
}
However if you still want to keep labelNumber1 as String, and to verify whether the value has been passed from ViewController1 during segue, add below line to viewDidLoad() of View2 ViewController.
class View2: UIViewController {
.....
override func viewDidLoad() {
super.viewDidLoad()
print("labelNumber1: \(labelNumber1)")
}
}
And you can see the printed value of labelNumber1 in the console.
HTH :)

Can't pass data between view controllers using segues (Xcode 7) (Swift)

I have been struggling to pass data between view controllers using segues. I have watched many youtube video tutorials and searched around on forums but I can't figure out why it won't work. I don't get any error messages but when I click the 'Button' the simulator crashes. I would love some help! Thanks!
Here is the code :
ViewController1 :
import UIKit
class ViewController: UIViewController {
#IBOutlet var textField: UITextField!
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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destViewController : ViewController2 = segue.destinationViewController as! ViewController2
destViewController.labelText = textField.text!
}
}
ViewController2 :
import Foundation
import UIKit
class ViewController2 : UIViewController {
#IBOutlet var Label: UILabel!
var labelText : String = ""
override func viewDidLoad() {
Label.text = labelText
}
}
StoryBoard Image :
storyboard image
As stated on the comment the problem was that you were using a push segue on a UIViewController.
Please note that push and modal segues are deprecated... Please take a look at this post entry and let me know if you have any doubts
What's the difference between all the Selection Segues?
Make sure to enter some text in your label textField before tapping the button since you are passing that label's text to next scene by using force unwrap.
destViewController.labelText = textField.text! //here compiler expects that your textField has the value
I made a sample project using your same code and didn't get an error. There's nothing wrong with your code.
Try this: Go to your storyboard and check outlets inspector for each view controller and make sure you don't have an outlet to nowhere.

Why two successive page opens with segue

when I am selected button twice will open a new page.
//////
Main viewController
var Country = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func taxiAction(sender: AnyObject) {
let opt = ["1","2","3","4","5"]
Country = opt
performSegueWithIdentifier("viewPlaceSegu", sender: sender)
}
...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// get a reference to the second view controller
if segue.identifier == "viewPlaceSegu" {
if let secondViewController = segue.destinationViewController as? TableViewPlace {
// set a variable in the second view controller with the String to pass
secondViewController.tnt = Country as! [String]
}
}
}
////
http://i.stack.imgur.com/LKrN7.jpg
I tried so but didn't realize problem .
Does anyone know about this? :)
A likely cause is that you have connected the segue from the button to the new ViewController in the storyboard. When the button is pressed it will load the segue created in storyboard as well as the one created programatically.
If this is the cause then you would just need to delete the storyboard segue and create a new one from the ViewController rather than from the button.

How to send my score variable to another view controller?

After I click on a button I go to a new view controller.
I made it possible to make points with var score = 0 in a IBOutlet and to show to points I use Score.text = "\(++score)".
How can I pass the score to the 'Game over' screen/view controller to a label called "resultScore"?
Add an attribute secondViewController in the destination view controller, and use prepareForSegue
Current View Controller
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as secondViewController;
svc.toPass = textField.text
}
}
in secondViewController you can define one variable like String
var toPass:String!
In the secondViewController under the viewDidLoad function add this code
println(\(toPass))
One easy way to achieve that is you can use NSUserDefault for that.
first of all in your playScene when you are increasing your score you can store your score this way:
Score.text = "\(++score)"
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "userScore")
After that in your next view controller you can get score this way:
resultScore = NSUserDefaults.standardUserDefaults().integerForKey("userScore")
Remember that type of your resultScore should be Int.
FirstViewController
#IBOutlet weak var textField: UITextField!
...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? GameOverViewController {
vc.score = Int(textField?.text)
}
}
...
SecondViewController
var score: Int!
#IBOutlet weak var label: UILabel!
...
override func viewDidLoad() {
super.viewDidLoad()
label.text = String(score)
}
This method will call when button was pressed, and in this place you may set some properties for your second view controller

SWIFT: No idea how to get back the selected value from a popover to the calling controller

I just going crazy on Swift Popover “return” values. I am new to Objectiv-C as well as SWIFT but I try to focus on SWIFT.
I checked out tutorials around Google and StackOverflow about how to manage iOS popovers, learned a lot but the last peace I couldn’t make it. It is great so see how easy it is made using Swift and Xcode 6, love it, but I could not figure out how to get back the selected value from my popover to my calling view controller.
So here is my problem:
(SIDENOTE: I am using SWIFT and do all using storyboard)
I have created a master ViewController with a button to select currencies. This button opens a “select currency” popover (linked to the CurrencyTableViewController (CTV) by CTRL-Dragging it to the CTV-Controller.
So far so good. The thing is, I have no idea how to get back the selected table row (currency) from the CTV-Table ;-( So I need the selected currency (table row) in the calling ViewController.
This is an excerpt from my ViewController (which is calling the popover)
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
[...]
// This button is calling the popover
#IBAction func buttonCurrency(sender: AnyObject) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let controller = segue.destinationViewController as? CurrencyTableViewController {
controller.popoverPresentationController?.delegate = self
return
}
}
[...]
Hopefully somebody can help me with that missing last mile how to get back the selected row value back to my ViewController.
Thanks in advance
Cheers
John
I made quick example, hope it helps:
// This is you popover's class
#objc protocol CurrencySelectedDelegate {
func currencySelected(currName: String)
}
class MyPopOverController: UIViewController {
weak var delegate: CurrencySelectedDelegate?
#IBAction func readyButtonPressed(sender: AnyObject) {
// Do what you want
delegate?.currencySelected("Euro/Dollar etc....")
// close popover
}
}
// ViewController
class ViewController: UIViewController, CurrencySelectedDelegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "mySegue" { // your identifier here
let controller = segue.destinationViewController as! MyPopOverController
controller.delegate = self
}
}
}
And remember just declare that currencySelected function in your ViewController.