Passing data between view controllers inside page view controllers in Swift - ios

Sorry if this particular problem has been asked about, I followed the answers on other threads but none of them seemed to work, but I just started learning Swift so all of this is pretty new to me.
So, I have a text field in two View Controllers and I want the third View Control to display a result based on the input from the other two controllers when I press a button.
I followed this tutorial and placed the text fields, label and button like I said before.
I placed my code (which you can see below) inside ViewControl.swift.
The problem is that when I attempt to run it I get a "Thread 1 :EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" error in the last two lines.
class ViewController: UIViewController {
var a: String = ""
var b: String = ""
#IBOutlet weak var aTextField: UITextField!
#IBOutlet weak var bTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultLabel: UILabel!
#IBAction func calculateButtonPressed(_ sender: UIButton) {
let a = aTextField.text!;
let b = bTextField.text!;
I think that the error is from the data not passing between the views (because before I had everything in the same view and it worked fine), but since I only have one ViewController.swift file I couldn't figure out how to use a Segue.

Do not declare same variables multiple times. Remove let before a & b . You have already declared a & b globally and then tried to redeclare it inside IBAction
class ViewController: UIViewController {
var a: String = ""
var b: String = ""
#IBOutlet weak var aTextField: UITextField!
#IBOutlet weak var bTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultLabel: UILabel!
#IBAction func calculateButtonPressed(_ sender: UIButton) {
a = aTextField.text!;
b = bTextField.text!;

Make sure your control outlets are setted properly.
In your two variables a & b are re-declared.Just update your code like below
#IBAction func calculateButtonPressed(_ sender: UIButton) {
self.a = aTextField.text!
self.b = bTextField.text!
}

Related

Looking to accept user input, and calculate a running total - Swift 5/Xcode

I am a beginner working on an app that will function like a golf scorecard. My first issue has come while attempting to accept user input in a (prototype) series of 9 textFields so the user can type in their scores, and then a textView at the end that is not editable that will show the total for the 9 holes. I am trying to get this to be a running total that updates constantly.
I tried passing the inputs from each textField into an array, and returning the sum of the array to a the textView, but still had issues with the data type from the textField being a string, where as I will only be dealing with integers.
My clunky first pass is as follows -
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var holeOneScore: UITextField!
#IBOutlet weak var holeTwoScore: UITextField!
#IBOutlet weak var holeThreeScore: UITextField!
#IBOutlet weak var holeFourScore: UITextField!
#IBOutlet weak var holeFiveScore: UITextField!
#IBOutlet weak var holeSixScore: UITextField!
#IBOutlet weak var holeSevenScore: UITextField!
#IBOutlet weak var holeEightScore: UITextField!
#IBOutlet weak var holeNineScore: UITextField!
#IBOutlet weak var totalForFrontNine: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Calculate Scores
#IBAction func calculate(_ sender: Any) {
let hole1:Int = Int(holeOneScore.text!)!
let hole2:Int = Int(holeTwoScore.text!)!
let hole3:Int = Int(holeThreeScore.text!)!
let hole4:Int = Int(holeFourScore.text!)!
let hole5:Int = Int(holeFiveScore.text!)!
let hole6:Int = Int(holeSixScore.text!)!
let hole7:Int = Int(holeSevenScore.text!)!
let hole8:Int = Int(holeEightScore.text!)!
let hole9:Int = Int(holeNineScore.text!)!
let totalArray = [hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8, hole9]
let totalScore = totalArray.reduce(0, +)
totalForFrontNine.text = String(totalScore)
print(totalForFrontNine!)
}
It worked, but barely. Any thoughts to modify this or a complete refresh is fine! I am not tied to anything as i am using this project to just teach me the basics.
Thanks in advance, cheers - glassGarrett
Like #jawadali mentioned, use IBOutletCollection. Here is a tutorial about how to use it.
As for the other issue,
...the data type from the textField being a string, where as I will only be dealing with integers.
A quick solution is to set the keyboardType of your textfield to UIKeyboardTypeNumberPad, or .numberPad in Swift.
textField.keyboardType = .numberPad
Or in storyboard,

Store user input and show into UITextView

I'm currently teaching myself in Swift and Xcode.
At the moment I'm trying to get some user input over a UITextField and I want to store them in an Array. The array should go through a for-loop to show the stored data in a UITextView.
At the start I tried it with one user input. It worked.
#IBOutlet weak var InputPlayerName: UITextField!
#IBOutlet weak var SubmitPlayer: UIButton!
#IBOutlet weak var ShowPlayerName: UITextView!
#IBOutlet weak var ShowSize: UITextView!
var players = [String]()
#IBAction func SubmittedPlayer(_ sender: Any) {
players.append(ShowPlayerName.text);
let playerssize = players.count;
ShowSize.text = "\(playerssize)";
for player in players {
if(playerssize == 1) {
ShowPlayerName.text = "Player: \n \(player)";
} else {
ShowPlayerName.text += "\(player)";
}
}
I don't get any errors, it just doesn't show me the results. But the arraysize grows if I press the button.
How can I show the Data line per line in the View?

Xcode shows a "Expected declaration" error with any variable put in

Been getting this error whenever I have a variable or pretty much anything else. For example here I put cpuString and when I called it I got the error
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var cpuLabel: UILabel!
#IBOutlet weak var coolerLabel: UILabel!
#IBOutlet weak var moBoLabel: UILabel!
#IBOutlet weak var ramLabel: UILabel!
#IBOutlet weak var gpuLabel: UILabel!
#IBOutlet weak var psuLabel: UILabel!
#IBOutlet weak var caseLabel: UILabel!
var cpuString = ""
cpuSting = "Intel i5" // Here is where I got the Expected declaration
}
No idea whats causing this. Funny thing is that Xcode is ignoring everything. When I try to do something with the labels it's like there not even there. When I start typing and the auto complete suggestions for things to put in it doesn't have my variables or anything else listed.
You need to move that assignment either to declaration or into valid scope:
1:
var cpuSting = "Intel i5"
2:
override func viewDidLoad() {
super.viewDidLoad()
cpuSting = "Intel i5"
}
What you do in your code is essentially attempting to make an assignment in an improper place. If you declare a variable, then just declare it with required initial value. If you want to re-assign a value, then just do that in the right place, such as in instance method scope like viewDidLoad.

Xcode - Pass data between view controllers, then cast to integer

I have a textfield in my first View Controller. The input is numbers only, but it's obviously in the form of a string. I've passed it to my second view controller. The code is as follows:
import Foundation
import UIKit
class View3on3Results : UIViewController {
#IBOutlet weak var APResult1: UILabel!
#IBOutlet weak var APResult2: UILabel!
#IBOutlet weak var APResult3: UILabel!
#IBOutlet weak var APResult4: UILabel!
var AP1: String? = String()
var AP2: String? = String()
var AP3: String? = String()
let x:Int? = Int(AP1)
override func viewDidLoad() {
APResult1.text = AP1
APResult2.text = AP2
}
}
I set the Label text to equal the strings I passed just to test if it was working; it is.
I'd now like to cast the strings I just passed to integers. I tried doing that with:
let x:Int? = Int(AP1)
It throws the error: View3on3Results.type does not have a member named 'AP1'. Anyone know what's up with this?
All coded in XCode 7.0 beta 3, using Swift 2.
You can not Initialise your instance that way but you can do that in viewDidLoad method this way:
let x:Int? = AP1?.toInt()

Getting values from various Labels and doing simple calculation

I am trying to program a simple app in Xcode using Swift.
I have two labels which contain INT values which are incremented up/down by the user using Steppers as per below:
class ViewController: UIViewController {
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
valueLabel.text = Int(sender.value).description
}
#IBOutlet weak var valueLabel2: UILabel!
#IBOutlet weak var stepper2: UIStepper!
#IBAction func stepperValueChanged2(sender: UIStepper) {
valueLabel2.text = Int(sender.value).description
}
I want to then have another Label (label3) which takes the INTs from label1 & label2 and divides them.
So for example if the user has Label1 as '5' and label2 as '10' I want label3 to display '0.5'.
Is there an easy way that I can do this?
As I'm sure you can tell, I'm really new to iOS development so any help or advice would be greatly appreciated!
Cheers!
Although this is a simple program you should still use best practice and adopt a model-view-controller design. Your model (data) should be separate from view (in essence the way the data is displayed). In a more 'serious' application the model would typically be a separate class, but in this case you can use local properties.
Storing data in Int properties also means you won't have to convert back from strings when you want to perform calculations.
class ViewController: UIViewController {
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBOutlet weak var valueLabel2: UILabel!
#IBOutlet weak var stepper2: UIStepper!
#IBOutlet weak var valueLabel3: UILabel!
var value1=0;
var value2=0;
#IBAction func stepperValueChanged(sender: UIStepper) {
self.value1=Int(sender.value);
self.valueLabel1.text="\(self.value1)";
self.updateResult();
}
#IBAction func stepperValueChanged2(sender: UIStepper) {
self.value2=Int(sender.value);
self.valueLabel1.text="\(self.value1)";
self.updateResult();
}
func updateResult {
if (self.value2 != 0) {
var result=Float(self.value1)/Float(self.value2)
self.valueLabel3.text="\(result)"
} else {
self.valueLabel3.text="Can't divide by 0"
}
}
}

Resources