TextField Empty Checking - ios

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 {
}
}

Related

How to check if a user inputed answer has letters, and if so, how would you just default that answer into a 0?

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

How to pass data from ViewDidLoad to a function of a button

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!"
}
}
}

Converting string value from text field to integer

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
}

Use of unresolved identifier, part of a single class

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.

Default parameter values error: "instance member cannot be used on type viewcontroller"

In my view controller:
class FoodAddViewController: UIViewController, UIPickerViewDataSource, UITextFieldDelegate, UIPickerViewDelegate {
let TAG = "FoodAddViewController"
// Retreive the managedObjectContext from AppDelegate
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
#IBOutlet weak var foodName: UITextField!
#IBOutlet weak var foodPortion: UITextField!
#IBOutlet weak var foodCalories: UITextField!
#IBOutlet weak var foodUnit: UILabel!
#IBOutlet weak var unitPicker: UIPickerView!
#IBOutlet weak var unitPickerViewContainer: UIVisualEffectView!
/*
unrelated code has been ommited
*/
func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
func validateTextField(textField: UITextField) -> Bool{
let correctColor = UIColor.redColor().CGColor, normalColor = UIColor.blackColor().CGColor
var correct = true
if textField == foodPortion || textField == foodCalories{
if !Misc.isInteger(textField.text!){
correct = false
}
}
if textField.text!.isEmpty {
correct = false
}
textField.layer.borderColor = correct ? normalColor : correctColor
return correct
}
}
I have a few textfields, and in my validateTextField can verify one at a time, and I want my validateAllTextFields be able to verify a give list of textfield by checking them one by one, if the list is not given, I want to check a given default list that contains all three textfield.
The code I imagine to be something like:
func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
However Xcode gives an error back:
instance member cannot be used on type viewcontroller
What's the cause and how to fix?
You cannot use instance variables in function declarations. Call the function with your textFields array and pass the parameters.
func validateAllTextFields(textFields: [UITextField] ) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
somehwere in your class:
validateAllTextFields(textFields: [foodName, foodPortion, foodCalories])
Or you check inside of your function if textFields is empty and than u use the instance variables
func validateAllTextFields(textFields: [UITextField] ) -> Bool {
if textFields.count == 0 {
textFields = [foodName, foodPortion, foodCalories]
}
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}

Resources