Swift - passing text and int from vc1 to vc 2 (uitextfield -> label in vc2) - swift

Passing only input text from textfield to label in second VC works!! But i want when user type number 10 in uitextfield, ( 1 ticket is 2 euros so 10 tickets * 2 euro is 20) and when i click PAY button, so that SUM can be displayed in label in second VC, i think that viewdidload in VC2 is happening before prepareForSegue, i don't know. It works when i click second time on PAY button, but not when i first click PAY button where label displays zero, help :) Embedded in navigation controller for navigation.
VC1
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var howManyTickets: UITextField!
var sumTicketsAndPriceOfTickets = Int()
var priceOfTicket = 2 // euros
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.
}
#IBAction func platiTeKarte(sender: AnyObject) {
sumTicketsAndPriceOfTickets = howManyTickets.text.toInt()! * priceOfTicket
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let driver = segue.destinationViewController as! primaocViewController
var whatToPass = sumTicketsAndPriceOfTickets
driver.receiver = whatToPass
}
}
VC2
import UIKit
class primaocViewController: UIViewController {
#IBOutlet weak var displaySum: UILabel!
var receiver:Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.displaySum.text = String(receiver)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

If your button is wired directly to a segue, then you don't need an #IBAction as well. As you are seeing, the prepareForSegue is happening before the #IBAction for your Pay button. Just compute your value in prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let driver = segue.destinationViewController as! primaocViewController
driver.receiver = (howManyTickets.text.toInt() ?? 0) * priceOfTicket
}
I changed the calculation of the pay to use the nil coalescing operator ??. This is generally a safer approach because if the toInt() returns nil for any reason, it will in this case just use 0 instead of crashing.

Related

How can I use a variable defined within a function in the main View Controller in another View Controller?

I'm developing a simple game (my first iOS app!) and am trying to link a variable between two View Controllers. In the first view controller, I have a textfield where the user can type in any number they choose. In the second View Controller, I would like users to be able to generate any number between 1 and the number they entered by pressing a button and be able to keep doing so. However, I am not able to use the "upperBound" variable holding the user-entered value in ViewController2.
I've tried using prepare for segue but it's not working, and I've snooped around stackoverflow and tried a couple of methods without quite knowing what I'm doing to no avail.
(UPDATED) ViewController:
class ViewController: UIViewController, UITextFieldDelegate {
//MARK: Properties
#IBOutlet weak var numberOfPages: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Handle the text field’s user input through delegate callbacks.
numberOfPages.delegate = self
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
//Save number entered and then randomly select a number within bounds
}
//MARK: Actions
var upperBound: Int?
#IBAction func setUpperBound(_ sender: UIButton) {
upperBound = Int(numberOfPages.text!)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Create a variable that you want to send
var newUpperBound = Int(upperBound!)
// Create a new variable to store the instance of ViewController2
let destinationVC = segue.destination as! ViewController2
destinationVC.upperBound = newUpperBound
}
}
(UPDATED) ViewController2:
class ViewController2: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
//Mark: Actions
#IBAction func roller(_ sender: UIButton) {
//Generate random number
let randomNumber = Int.random(in: 0 ..< upperBound)
}
var upperBound: Int?
}
With this code, I'm getting an error on line 34 of ViewController2 that reads "Use of unresolved identifier upperBound". Additionally, there is an issue on line 40 of ViewController that reads "immutable value upperBound was never used". I would expect to be able to generate a random value between 1 and the entered number so that I can keep working and add more features to my app (like printing these random values etc)
ViewController
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var numberOfPages: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
numberOfPages.delegate = self
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
//Save number entered and then randomly select a number within bounds
}
//MARK: Actions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if numberOfPages.text == ""{
print("Please enter number")
return
}
let upperBound: Int? = Int(numberOfPages.text ?? "0")
if upperBound != 0{
if segue.identifier == "mySegue"{
let vc = segue.destination as! ViewController2
vc.upperBound = upperBound
}
}
}
}
ViewController2
import UIKit
class ViewController2: UIViewController {
#IBOutlet weak var lbl_UpperBound: UILabel!
#IBOutlet weak var btn_Generate: UIButton!
#IBOutlet weak var lbl_Random: UILabel!
var upperBound: Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
lbl_UpperBound.text = "Upper Bound - \(upperBound ?? 0)"
btn_Generate.addTarget(self, action: #selector(roller), for: .touchUpInside)
lbl_Random.text = ""
}
#objc func roller(_ sender: UIButton) {
//Generate random number
let randomNumber = Int.random(in: 0 ..< (upperBound ?? 1))
lbl_Random.text = "\(randomNumber)"
}
}
Also Don't forget to name the Segue

Passing Data through multiple View Controllers with segue [Swift 3.0 Xcode]

NOTE: Question has been edited in an attempt to be more clear with my issue.
Hey, I am trying to pass data through multiple VCS. I want to pass data (arrays) from V2 -> V3 and then V3 -> V1 but I want to be able to only navigate through the VCs as such: V1 - V2 - V3 and V3 - V2 - V1.
So what I need to learn is how to pass data without navigating to a different VC as well as setting up two preparetosegue methods to pass data between V2 -> V3 and V3 -> V1 while also being able to navigate between all VCs. When I create my first preparetosegue, I am unable to use other segues associated in my VC to navigate to other VCs without getting a Fatal Error.
Can anyone help me?
Any input would be greatly appreciated!
Heres my attempt:
import UIKit
class ViewController: UIViewController {
var name = String()
var StopButInfo = [String]()
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 StringArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBOutlet var PHeight: UITextField!
#IBOutlet var PName: UITextField!
#IBAction func Search(_ sender: Any) {
if PHeight.text != ""{
performSegue(withIdentifier: "SearchSegue", sender: self)}
let CDstart = String(describing: Date())
StringArray.append(CDstart)
StringArray.append(PName.text!)
StringArray.append(PHeight.text!)
}
override func prepare(for SearchSegue: UIStoryboardSegue, sender: Any?){
let thirdController = SearchSegue.destination as! ThirdViewController
thirdController.SearchButInfo = StringArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class ThirdViewController: UIViewController {
var height = String()
var SearchButInfo = [String]()
var StringArray = [String]()
#IBAction func Stop(_ sender: Any) {
if StringArray.count != 0{
performSegue(withIdentifier: "SegueToStart", sender: self)
}
let CDStop = String(describing: Date())
StringArray.append(CDStop)
StringArray.append(height)
}
override func prepare(for SegueToStart: UIStoryboardSegue, sender: Any?){
let firstController = SegueToStart.destination as! ViewController
firstController.StopButInfo = StringArray}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to check which view controller's segue is about to be performed, this can be done like this inside prepare(for segueMVH: UIStoryboardSegue, sender: Any?) method:
if let firstController = segueMVH.destination as! FirstViewController {
// Set first view controller's data
} else if let secondController = segueMVH.destination as! SecondViewController {
// Set second view controller's data
} else if let thirdController = segueMVH.destination as! ThirdViewController {
// Set third view controller's data
}
Note: It's better to use a different identifier for each segue to be able to distinguish between them.
The error you got on let secondController = segueMVH.destination as! ThirdViewController is saying that you are casing HC.ViewController into ThirdViewController and that's why it failed. It means that the destination view controller of your segue is not ThirdViewController.
To further help you understand segue: A segue is a connection between a source view controller and a destination view controller and can be only used between them two. See this picture:
In this case, I have a segue connection in my storyboard connected between my VC1's button and VC2. In this case, my button click will trigger this segue and prepare(for segue) method can only be in VC1 where it passes data to VC2.
So in your situation, you believe that the destination of your segue is ThirdViewController but it's actually not. So please check your segue with identifier segueMVH to see if it is connected between your current view controller and your ThirdViewController.
Hope this helps

Unable to send an int value between view controller and table view controller in swift

the class PreferencesViewController sends nil through prepare for segue regardless if IBActions are taken or not. It seems that something is wrong in my prepare for segue but I'm not sure. I'm not trying to assign to any label or anything I'm just trying to send the int value to another variable in the class Pick2_1. Thanks in adavance
import UIKit
class PreferencesViewController: UIViewController {
var preference = 0
#IBAction func nImportant(sender: UIButton) {
preference = -1
print(preference)
}
#IBAction func N(sender: UIButton) {
preference = 0
print(preference)
}
#IBAction func mImportant(sender: UIButton) {
preference = 1
print(preference)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "preferenceSegue" {
let preferenceVC = segue.destinationViewController as! Pick2_1
preferenceVC.preferenceSent = preference
print(preference)
}
}
}
Ok segue is directly connected to the button. You have to set the segue between your 2 controllers set the identifier and in the #IBAction you should call performSegueWithIdentifier func

Delegate using Container View in Swift

I'm developing an app for iPad Pro. In this app, containerView use to add additional views and interact with them.
First, I created a protocol:
protocol DataViewDelegate {
func setTouch(touch: Bool)
}
Then, I created my first view controller
import UIKit
class ViewController: UIViewController, DataViewDelegate {
#IBOutlet var container: UIView!
#IBOutlet var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func setTouch(touch: Bool) {
if touch == true {
labelText.text = "Touch!"
}
}
}
And finally, I created a view that will be embedded in containerView.
import UIKit
class ContainerViewController: UIViewController {
var dataViewDelegate: DataViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func touchMe(sender: AnyObject) {
dataViewDelegate?. setTouch(true)
}
}
But for some reason, nothing happened, the first view controller receives nothing in setTouch function.
My question is: In this case, using container, how can I make the communication between two ViewsControllers?
Like #nwales said you haven't yet set the delegate. You should do set the delegate in prepareForSegue function on your first viewController (who contain the viewContainer)
First select the embed segue and set an identifier in the attributes inspector.
Then in the parentViewController implement the func prepareForSegue like this:
Swift 4+:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "the identifier") {
let embedVC = segue.destination as! ViewController
embedVC.delegate = self
}
}
Below:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "the identifier") {
let embedVC = segue.destinationViewController as! ContainerViewController
embedVC.dataViewDelegate = self
}
}
Looks like you defined the delegate, but have not set the delegate. This happens to me all the time.

Linking View Controllers through button

I'm a beginner at all of this...Having said that I've come across a point in my app where I've stalled and don't know what to do or fix next. So any answers would be appreciated!
So in my Home View Controller, I have four buttons with four different categories.
Each of these categories has its own question list, but they have a common "General Question" list. The general question list has its own view controller.
When you click on any of the four buttons, it brings you to the General Question view. At the bottom of this view, I have a "Next" button.
Goal: Configure the Next button to continue to one of the category's question list based on what is initially pressed in the Home View Controller.
I've connected the buttons via outlet and action in the View Controller.
However, the Next button will not connect when I control + drag into the View Controller. I'm not sure where I need to put the code for this...
I was thinking that the code for the Next button might need to have some kind of conditional statement, but since it won't connect I can't even get that far.
Help!
(This is what I have) Sample Code:
import UIKit
import AddressBookUI
import AddressBook
import Foundation
import CoreData
import CoreGraphics
import EventKit
import EventKitUI
import CoreFoundation
class ViewController: UIViewController {
#IBOutlet var ColorButton: UIButton!
#IBOutlet var StyleButton: UIButton!
#IBOutlet var CutButton: UIButton!
#IBOutlet var MakeupButton: UIButton!
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.
}
var eventstore: EKEventStore!
var event: EKEvent!
weak var editViewDelegate: EKEventEditViewDelegate!
#IBAction func ColorButtonPressed(sender: UIButton) {
}
#IBAction func StyleButtonPressed(sender: UIButton) {
}
#IBAction func HaircutButtonPressed(sender: UIButton) {
}
#IBAction func MakeupButtonPressed(sender: UIButton) {
}
}
Here is a suggested approach as shown in the code below for 2 controllers (instead of 4) for brevity. Use appropriate named segues to each of the "next processing" controllers from the common processing controller and set up a chain. Here is a link to the project file: Project file
import UIKit
class ViewController: UIViewController {
var nextVcId = 0 // defines the button that is pressed
#IBAction func unwindFromOtherControllers(segue: UIStoryboardSegue) {
// In case you want to get back to the main VC
}
#IBAction func btn2Action(sender: UIButton) {
nextVcId = 0
self.performSegueWithIdentifier("commonSegue", sender: sender)
}
#IBAction func btn1Action(sender: UIButton) {
nextVcId = 1
self.performSegueWithIdentifier("commonSegue", sender: sender)
}
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 vc = segue.destinationViewController as! CommonViewController
vc.nextControllerId = nextVcId
}
}
import UIKit
class CommonViewController: UIViewController {
var nextControllerId = 0
#IBOutlet weak var StatusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.StatusLabel.text = "Common"
commonProcessing()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func commonProcessing() {
// do your common processing
if nextControllerId == 0 {
performSegueWithIdentifier("next1Segue", sender: self)
} else {
performSegueWithIdentifier("next2Segue", sender: self)
}
}
}
import UIKit
class Next1ViewController: UIViewController {
#IBOutlet weak var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.statusLabel.text = "Next1"
next1Processing()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func next1Processing() {
println("Next 1 Processing")
}
}
import UIKit
class Next2ViewController: UIViewController {
#IBOutlet weak var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
statusLabel.text = "Next 2"
next2Processing()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func next2Processing() {
println("Next 2 Processing")
}
}
processing