Sum of UITextfield values crashes when any field is left blank - ios

Screenshot of simulator screen
Hello all. I just recently started trying to learn coding in Swift 2. I am trying to make a very simple app where I can add scores, push my "calculate" button and display the total in a label. I was able to do that as seen in the screenshot. The problem I have is if I don't put a score in one of the textfields and still try to calculate it, it crashes. This is my code:
class ViewController: UIViewController {
#IBOutlet weak var score1: UITextField!
#IBOutlet weak var score2: UITextField!
#IBOutlet weak var score3: UITextField!
#IBOutlet weak var total: UILabel!
#IBAction func Calculate(sender: AnyObject) {
let score1 = Int(score1.text!)!
let score2 = Int(score2.text!)!
let score3 = Int(score3.text!)!
let alltogether = (scoreone) + (scoretwo) + (scorethree)
total.text = "Your total score is \(alltogether)!"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
Could someone point me in the direction I need to look. I am thinking I need to add some sort of exemption if the field is nil. Or something along the lines of making the default int 0??? Thank you all!

let score1 : Int = Int(score1.text ?? "") ?? 0
let score2 : Int = Int(score2.text ?? "") ?? 0
let score3 : Int = Int(score3.text ?? "") ?? 0
This will yield value 0 in case your fields are empty or otherwise non-numerical (or if UITextField property .text contains nil).

Related

Use swift stepper to multiply my original number not previous number

Here's my code.
My need is if the price label have had number
When pressing add from stepper
I need stepper value to multiply my price number
but I encounter this situation
The price label won't multiply my original number
like if price number originally is 50
I would like to show 50,100,150,200,250
not like this 50 ,100 ,300,400
#IBOutlet weak var stepperValue: UILabel!
#IBOutlet weak var price: UILabel!
#IBAction func stepper(_ sender: UIStepper) {
let count = Int(sender.value)
stepperValue.text = String(count)
let price = Int(price.text!)!
price.text? = String(price * count)
}
Is there proper way to solve my logical problem?
You need to store original value somewhere and use it for incrementation.
E.g.
#IBOutlet weak var stepperValue: UILabel!
#IBOutlet weak var price: UILabel!
private var originalPrice: Int = 50 // or whatever you want
#IBAction func stepper(_ sender: UIStepper) {
let count = Int(sender.value)
stepperValue.text = String(count)
price.text = String(originalPrice * count)
}

use array element as var UILabel name in swift

I'm trying to build a key/values pair, for referencing later.
The array will hold a index reference, and it's values inside. One of the values is a video matching the index, and the other value is the corresponding label name (so I can change the color when video is played).
Here is my code:
class ViewController: UIViewController {
var videos = [5: ["urltovideo1", "locationOne"], 7: ["urltovideo2", "locationTwo"]]
var bg: UILabel!
#IBOutlet weak var locationOne: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
bg = videos[5]![1]
bg.backgroundColor = UIColor.green
}
}
I get an error "Cannot assign value of type 'String' to type 'UILabel!'"
I tried "bg = UILabel(videos[5]![1])" and get an error ""Argument labels '(_:)' do not match any available overloads""
Any ideas on how to fix it or better way to implement this?
Here is a solution for you:
#objc var locationOne: UILabel!
#objc var locationTwo: UILabel!
var videos = [5: ["urltovideo1", "locationOne"], 7: ["urltovideo2", "locationTwo"]]
var bg: UILabel! = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
if let bg = self.value(forKey: videos[5]![1]) as? UILabel {
bg.backgroundColor = UIColor.green
}
}
#objc is required to make self.value(forKey:) working properly - you have to add it for every property you want to access via this method.

Swift code to make second textfield clear when typing in the second one

I am teaching myself swift for about a week and a half. I am trying to make a converter that goes from inch to centimeters. I have two textfields, one to punch in inches and one for centimeters. When you type one of them in you hit calculate and it gives you either the conversion for inches or centimeters. The problem I am running into is if you fill one in and then you decide you would rather see the other unit of measure, the numbers are still inputed and the button doesn't really work. How can I have the textfield clear if the user decides to use the other field instead?
Also didn't know if it was possible with the code I am uploading, but I would prefer to get rid of the conversion button all together, so when the user types on unit or the other it immediately fills out the label below. is this possible?
here is the code so far.
import UIKit
class ViewController: UIViewController, UITextViewDelegate{
#IBOutlet weak var InchesField: UITextField!
#IBOutlet weak var CentimetersField: UITextField!
#IBOutlet weak var ConversionLabel: UILabel!
//Only let 1 decimal point
let numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
#IBAction func ConversionButton1(_ sender: AnyObject) {
if InchesField.text == "" || CentimetersField.text == "" {
//either inchfield or centimetersfield text is empty
ConversionLabel.text = String("Please enter a number")
}
if let text = InchesField.text, !text.isEmpty
{
//do something if it's not empty
let inch = Double(InchesField.text!)
let inCmConvertor = inch! * 2.54
ConversionLabel.text = String("\(inCmConvertor) Centimters")
} else
if let text = CentimetersField.text, !text.isEmpty
{
let centimeter = Double(CentimetersField.text!)
let cmInConvertor = centimeter! / 2.54
ConversionLabel.text = String("\(cmInConvertor) Inches")
}
}
}
Heres a screenshot
What you want to do is create an IBAction for each Text Field with the Editing Changed event in the IBAction creation window.
I tested the code below and it worked:
#IBOutlet weak var InchesField: UITextField!
#IBOutlet weak var CentimetersField: UITextField!
#IBAction func InchesFieldChanged(_ sender: Any) {
CentimetersField.text = ""
}
#IBAction func CentimetersFieldChanged(_ sender: Any) {
InchesField.text = ""
}
Don't copy and paste the code, just create the IBActions manually, it will be much simpler.
Good luck with your journey into Swift programming and iOS development.

Unable to display text from a double to a string

I'm having an issue with a simple app for iOS 9.
When I press the calculate button, the app closes and it will not change the text of the label.
What did I do wrong?
class ViewController: UIViewController {
#IBOutlet weak var weightTextField: UITextField!
#IBOutlet weak var repsTextField: UITextField!
#IBOutlet weak var resultsLabel: UILabel!
#IBAction func calculateButton(sender: AnyObject) {
let numberOfReps = Double(repsTextField.text!)!
let weight = Double(weightTextField.text!)!
let x = (numberOfReps * 0.033)
let x1 = (x + 1)
let max = (weight * x1)
let oneMaxRepString = Double(max)
resultsLabel.text = String(oneMaxRepString)
}
}
#rogue-studios is right. You didn't connect IBOutlets correctly.
I assume that your code would work. Your app could be crashing because your connection between labels/buttons are not connected correctly. Go and make sure that your #IBOutlets are connected to the storyboard objects.
If this does not work, comment the error that you are getting in the console.

Adding numbers from Textfields with other numbers in Textfields

Right now I have 3 Textfields where users can input numbers and I want to have all 3 textfields be added together and broadcasted into either another label or textfields later down the page. Is this something that can be done?
Right now I have the following for the 3 textfields
#IBOutlet var waistText1: UITextField!
#IBOutlet var waistText2: UITextField!
#IBOutlet var waistText3: UITextField!
and for the label where the data needs to go;
#IBOutlet var wavgText: UILabel!
My first idea was something like;
wavgText.text = waistText1 + waistText2 + waistText3;
Just parse the textfields text as integer, add the values and convert back to string.
#IBOutlet var valueLabel: UILabel!
func updateValueLabel() {
let number1 = Int(waistText1?.text ?? "") ?? 0
let number2 = Int(waistText2?.text ?? "") ?? 0
let number3 = Int(waistText3?.text ?? "") ?? 0
valueLabel.text = String(number1 + number2 + number3)
}

Resources