I know that there are already some answers about this, but none of them seem to solve my issue as they talk about variables or constants being identified in other classes, but mine isn't.
Here is my viewcontroller.swift (I have not made code in any other files)
class ViewController: UIViewController, UITextFieldDelegate {
// MARK: Properties
#IBOutlet weak var textFieldA: UITextField!
#IBOutlet weak var textFieldB: UITextField!
#IBOutlet weak var textFieldC: UITextField!
#IBOutlet weak var answerLabel: UILabel!
#IBOutlet weak var answerLabelNegative: UILabel!
#IBOutlet weak var whatEquation: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textFieldA.delegate = self
textFieldB.delegate = self
textFieldC.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textFieldA.resignFirstResponder()
textFieldB.resignFirstResponder()
textFieldC.resignFirstResponder()
return true
}
// MARK: Actions
#IBAction func solveButton(sender: AnyObject) {
let a:Double! = Double(textFieldA.text!) // textfieldA is UITextField
let b:Double! = Double(textFieldB.text!) // textfieldB is UITextField
let c:Double! = Double(textFieldC.text!) // textFieldC is UITextField
let z: Double = (b * b) + 4 * a * c
answerLabel.text = "Positive equation x = \(-b + (sqrt(z) / 2 * a))"
answerLabelNegative.text = "Negative equation x = \(-b - (sqrt(z) / 2 * a))"
// These conditional statements are used to determine whether a + or a - should be infron of th number
if a < 0 {
let aValue: String = "-"
} else {
let aValue: String = " "
}
if b < 0 {
let bValue: String = "-"
} else {
let bValue: String = " "
}
if c < 0 {
let cValue: String = "-"
} else {
let cValue: String = " "
}
whatEquation.text = "\(aValue)\(a) \(bValue)\(b) \(cValue)\(c)" //This is where the error occurs, on the "whatEquation.text" line
}
}
You're defining aValue, bValue and cValue inside of the if statements so they only exist inside of the if statements where they are defined and aren't visible to your last line where they set the text.
You should change it so they are defined in a scope where your last line can see them.
let aValue = a < 0 ? "-" : " "
let bValue = b < 0 ? "-" : " "
let cValue = c < 0 ? "-" : " "
whatEquation.text = "\(aValue)\(a) \(bValue)\(b) \(cValue)\(c)"
aValue, bValue and cValue are defined in the if scope and cannot be accessed outside the if block. You need to define them below your #IBOutlet definitions (as global variables) so u can use them anywhere in your code.
var aValue: String!
var bValue: String!
var cValue: String!
And in your if block remove the let when you are assigning the text to the a b and c values.
Related
Heres the code I have so far, now when a user inputs any letter, my label display nothing, what I would like to figure out is how to turn that nothing "", into a 0. I tried doing an if statement on my "label.txt ="'s but that didn't pan out. What would be a better way of finding my desired results?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let positiveArray = gameResultsArray.filter {
(item: Int) -> Bool in return item > 0
}
var avgArrayValue = 0
if positiveArray.count == 0
{
avgArrayValue = 0
}else {
avgArrayValue = sumArray / positiveArray.count
}
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
Here is what you need, convert String to Int and give the default 0. Instead of using the guard let return use this method:
Instead of this:
guard let game1Results = Int(text1) else { return }
Use this:
let game1Results = Int(text1) ?? 0
I have two Random numbers generating in ViewDidLoad. I Want to plus these two numbers and the result should be checked in a button with data of a input field. my problem is that I do not know how to transfer result to the function CheckResultBtn . now it does not recognise result.
here is My codes and I really appreciate any kinds of help
class ViewController: UIViewController {
#IBOutlet weak var lblRandomNumOne: UILabel!
#IBOutlet weak var lblRandomNumTwo: UILabel!
#IBOutlet weak var KidsField: UITextField!
#IBOutlet weak var Showresult: UILabel!
#IBOutlet weak var CheckResult: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
let result = x + y;
CheckResultBtn(result) //not sure about this
}
#IBAction func CheckResultBtn(_ sender: Any)
{
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
}
declare the variable "result" before the viewDidload function
var result : Int!
then proceed to perform the operation on the variable in your viewDidload and you can get rid of this line
CheckResultBtn(result)
and you should be able to access the result variable in your IBAction function
You can try
#IBAction func checkResultBtn(_ sender: Any) {
displayRes(Int(kidsField.text!)!)
}
func displayRes(_ result:Int) {
showresult.text = result == kidsresult ? "Bravo" : "Try Again!"
}
Then inside viewDidLoad
displayRes(x+y)
create a new function instead of using action Method
like this :
func CheckResultBtn(_ result : Int) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
or create a variable
var result : Int?
assign a value
result = x + y;
and use inside the action Method
var result : Int?
override func viewDidLoad() {
super.viewDidLoad()
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
result = x + y;
}
#IBAction func CheckResultBtn(_ sender: Any) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
I am new to Swift but I have managed to setup some code for an OTP authentication page but I need help recreating the code.
I want to have the textfields setup into an array and when I get a value (ex "123456") I want to split the numbers 6 ways and add 1 digit per textfield (1,2,3,4,5,6) and vice versa. How do I go about doing this?
Right now my code for my current setup is:
import UIKit
import FirebaseAuth
class PhoneAuthenticationViewController: UIViewController {
#IBOutlet weak var Auth1: UITextField!
#IBOutlet weak var Auth2: UITextField!
#IBOutlet weak var Auth3: UITextField!
#IBOutlet weak var Auth4: UITextField!
#IBOutlet weak var Auth5: UITextField!
#IBOutlet weak var Auth6: UITextField!
#IBAction func textEditDidBegin(_ sender: UITextField) {
print("textEditDidBegin has been pressed")
if !(sender.text?.isEmpty)!{
sender.selectAll(self)
//buttonUnSelected()
}else{
print("Empty")
sender.text = " "
}
}
#IBAction func textEditChanged(_ sender: UITextField) {
print("textEditChanged has been pressed")
let count = sender.text?.count
//
if count == 1{
switch sender {
case Auth1:
Auth2.becomeFirstResponder()
case Auth2:
Auth3.becomeFirstResponder()
case Auth3:
Auth4.becomeFirstResponder()
case Auth4:
Auth5.becomeFirstResponder()
case Auth5:
Auth6.becomeFirstResponder()
case Auth6:
Auth6.resignFirstResponder()
default:
print("default")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
Auth1.delegate = self
Auth2.delegate = self
Auth3.delegate = self
Auth4.delegate = self
Auth5.delegate = self
Auth6.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Auth1.becomeFirstResponder()
}
}
Try this code if this helps you
import UIKit
/// Extension for String
extension String {
/// Function which will split string in parts
func splitInParts() -> [String]{
/// Array
var splittedArray = [String]()
/// Split STring according to characters
for char in self {
/// Append character as string
splittedArray.append(String(char))
}
/// Return
return splittedArray
}
}
class TwoScrollViewStack: UIViewController {
/// OTP String
var myString : String = "123456"
/// Labels
private var otp1 = UILabel()
private var otp2 = UILabel()
private var otp3 = UILabel()
private var otp4 = UILabel()
private var otp5 = UILabel()
private var otp6 = UILabel()
/// Label Array
private var labelArray = [UILabel]()
override func viewDidLoad() {
super.viewDidLoad()
/// Assign Label in Array
labelArray = [otp1,otp2,otp3,otp4,otp5,otp6]
/// Get Splitted String
let splittedStringArray = self.myString.splitInParts()
/// Sssign Values to Labels
for i in 0..<splittedStringArray.count {
labelArray[i].text = splittedStringArray[i]
}
/// Check Output if necessary
print(splittedStringArray)
/// Output - ["1", "2", "3", "4", "5", "6"]
}
}
in below code,
switch sender {
case Auth1:
// add your logic to append entered character into auth1 textfield.
Auth1.text = sender.text ?? ""
Auth2.becomeFirstResponder()
...
// same in all case
...
}
I'm really new to Swift and I am having problems with the conversion of a string (entered in a text field) to an integer.
I'm trying to create a small calculation app (I was following a tutorial on YouTube but it's old).
My app has 3 text fields, a label (that is meant to display the result), and a button to start the calculation.
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var valueA: UITextField!
#IBOutlet weak var valueB: UITextField!
#IBOutlet weak var valueC: UITextField!
#IBOutlet weak var result: UILabel!
#IBAction func calculateTotal(_ sender: Any) {
var a:Int? = Int(valueA.text)
var b:Int? = Int(valueB.text)
var c:Int? = Int(valueC.text)
var answer = a! * b! * c!
}
}
Try this (crash free code and you can add n number of textfield/string values as a number string):
var arrayOfTextFieldValues = [valueA.text, valueB.text, valueC.text]
#IBAction func calculateTotal(_ sender: Any) {
if let multiplication = multiplication(arrayString: arrayOfTextFieldValues) {
print("Answer = \(multiplication)")
result.text = "\(multiplication)"
}
}
// handle operations
func multiplication(arrayString: [String?]) -> Int? {
var answer:Int?
for arrayElement in arrayString {
if let stringValue = arrayElement, let intValue = Int(stringValue) {
answer = (answer ?? 1) * intValue
}
}
return answer
}
I want to add value of textfield. I want to check textfield is empty or not or checking other value than int. I am newer in Swift. Please help any help would be apperciated.
#IBOutlet var label :UILabel!
#IBOutlet var first : UITextField!
#IBOutlet var third : UITextField!
#IBOutlet var second : UITextField!
var bloa :NSString?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func playPressed(sender: UIButton) {
var a: Int = 0
var b: Int = 0
var c: Int = 0
var d: Int = 0
if first.text!.isEmpty || second.text!.isEmpty || third.text!.isEmpty {
return
}
else
{
// If on first textfield there is another value than int they show
//fatal error: unexpectedly found nil while unwrapping an Optional value
a = (Int)(first.text!)!
b = Int(second.text!)!
c = Int(third.text!)!
d = a + b + c
label?.text = String (format: "%d",d)
}
Try this:
if first!.text == "" || second!.text == "" || third!.text == "" {
}
You don't need to check if it is empty or not this way:
guard let a = Int((first?.text)!), b = Int((second?.text)!) , c = Int((third?.text)!) else {
print("Not convertable to Int or field are empty")
return
}
And your final code will be:
import UIKit
class ViewController: UIViewController {
#IBOutlet var label :UILabel?
#IBOutlet var first : UITextField?
#IBOutlet var third : UITextField?
#IBOutlet var second : UITextField?
override func viewDidLoad() {
playBackgroundMusic("Naughty_Boy.mp3")
}
#IBAction func playPressed(sender: UIButton) {
guard let a = Int((first?.text)!), b = Int((second?.text)!) , c = Int((third?.text)!) else {
print("Not convertable to Int or field are empty")
return
}
let d = a + b + c
label?.text = String (format: "%d",d)
}
}
If you set the keyboard for all these text boxes as below screenshot and change is marked in red rectangle. You don't need to check the given character/word is integer or not in the code.
Set your keyboard type to Number Pad from the Storyboard. then do this in code:
#IBAction func playPressed(sender: UIButton) {
if first?.text?.isEmpty || second?.text?.isEmpty || third?.text?.isEmpty {
}
}