I'm trying to calculate two values from two UITextFields. What I did was made the answerScreen equal to the valueOne which I turned into an Int and valueTwo which is supposed to be the opposite of an var with the !. Can somebody tell me what I'm doing wrong?
import UIKit
class ViewController: UIViewController {
// The answer will be here
#IBOutlet weak var answerScreen: UILabel!
// The first number
#IBOutlet weak var valueOne: UITextField!
// The second number
#IBOutlet weak var valueTwo: UITextField!
// The equals button
#IBAction func calculateValues(sender: AnyObject) {
answerScreen.text = valueOne.text.toInt() * valueTwo!
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
let result = (valueOne.text.toInt() ?? 0) * (valueTwo.text.toInt() ?? 0)
answerScreen.text = "\(result)"
Will convert the text field values to Int or use 0 if the conversion failed.
One Can try
var temp = (firstTextField.text! as NSString).integerValue * (secondTextField.text! as NSString).integerValue
For setting value to UILabel
self.resultLable.text = String("\((firstTextField.text! as NSString).integerValue * (secondTextField.text! as NSString).integerValue)")
Related
I am newbie in coding. I just started to learn #swift and trying yo make a calculation app. My problem is my UITextField doesn't work with dot or comma.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var ilkLabel: UITextField!
#IBOutlet weak var ikinciLabel: UITextField!
#IBOutlet weak var sonucLabel: UILabel!
#IBOutlet weak var ilk2Label: UITextField!
#IBOutlet weak var ikinci2Label: UITextField!
#IBOutlet weak var sonuc2Label: UILabel!
#IBOutlet weak var ilk3Label: UITextField!
#IBOutlet weak var ikinci3Label: UITextField!
#IBOutlet weak var sonuc3Label: UILabel!
var sonuc:Double = 0
var sonuc2:Double = 0
var sonuc3:Double = 0
var deneme:Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
#IBAction func plusBtn(_ sender: Any) {
func forTrailingZero(temp: Double) -> String {
let tempVar = String(format: "%g", temp)
return tempVar
}
deneme = Double(Int(ikinciLabel.text!)! + 100 / 100 * Int(ilkLabel.text!)!)
sonucLabel.text = String(forTrailingZero(temp: Double(ikinciLabel.text!)! / 14.56 ) )
}
#IBAction func plus2Btn(_ sender: Any) {
}
#IBAction func plus3Btn(_ sender: Any) {
}
}
I expect to make calculation like 1.4 + 2.35 but when i try the app crashes. I can only calculate whole number like 2 + 2.
#matt is right. If the text in ikinciLabel is not an Int, the app crashes. You tell it to crash by using the force unwrap operator: !.
In general
You should only force-unwrap things when you are absolutely sure that the thing you want to unwrap is not nill. In all other cases you should if-let or guard-let the optional, use the nil-coalescing operator (??) (or other ways to unwrap optionals) and handle the nil-case.
In your case
if you want to allow the user to enter floating point numbers using either a comma or a dot, you could simply replace every comma with a dot like so:
let enteredTextWithoutComma = textField.text?.replacingOccurrences(of: ",", with: ".")
This new constant is an optional. To safely make a Double out of it, do:
guard let enteredTextWithoutCommaUnwraped = enteredTextWithoutComma,
let enteredNumber = Double(enteredTextWithoutCommaUnwraped) else {
// one of the two actions didn't work. Maybe the entered phrase was not a number
// do something
return
}
// here you can use the variable enteredNumber. It is now a Double (not an Optional)
...
I am new in the developer world and have been on and off since february with swift and Xcode. I am hoping someone could help me out. Im trying to make a simple tip calculator and can't seem to * two uilabels together. this is what i have so far... at the total.text = "(totalAmount) * (tipPercent)" ... thanks any help would be great. :)
#IBOutlet weak var totalAmount: UILabel!
#IBOutlet weak var textFIeld: UITextField!
#IBOutlet weak var tipPercent: UILabel!
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var total: UILabel!
#IBOutlet weak var tip: UILabel!
#IBAction func sliderChanged(_ sender: UISlider) {
sldr()
total.text = "\(totalAmount) * \(tipPercent)"
}
#IBAction func buttonPressed(_ sender: Any) {
ttl()
}
func ttl() {
if let grandTotal = textFIeld.text {
totalAmount.text! = "\(grandTotal)"
}
}
func sldr() {
tipPercent.text! = "\(Int(slider.value))"
}
The below expression will just only return you a string without any multiplication that you are expecting.
total.text = "\(totalAmount) * \(tipPercent)"
You know how to unwrap the text as you have done in ttl. You should use the same approach here
if let totalTxt = totalAmount.text, let percentTxt = tipPercent.text {
//Then change to whatever scalar type you want
if let totalAmount = Float(totalTxt), let percent = Float(percentTxt) {
let totalBill = totalAmount * percent
total.text = "\(totalBill)"
}
}
Im trying to make this calculator for various math formulas and I'm stuck at this point. I was following this tutorial
Here's my code:
import UIKit
class pythagorasViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var bLabel: UILabel!
#IBOutlet weak var aField: UITextField!
#IBOutlet weak var bField: UITextField!
#IBOutlet weak var answerLabel: UILabel!
#IBAction func calculateButton(_ sender: UIButton) {
var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue
var answer = sqrt(a*a + b*b)
answerLabel.text = "\(answer)"
}
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.
}
}
The part where I'm getting the error is at:
var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue
Prefer let to var when possible. You do not need to use NSString. You can cast String to Float?. You need to unwrap both the text property which is a String? (if you have a question about the type of a variable option click and it will show you) and the Float? conversion:
func calculateButton(_ sender: UIButton) {
guard let aText = aField.text,
let bText = bField.text,
let a = Float(aText),
let b = Float(bText) else {
return
}
let answer = sqrt(a*a + b*b)
answerLabel.text = "\(answer)"
}
I have just started learning swift ios development. I am encountering this problem which I am not able to solve. Can someone please tell what I am doing wrong? The image below contains screenshot of the error.
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var dayPicker: UIPickerView!
#IBOutlet weak var addButton: UIButton!
#IBOutlet weak var textField: UITextField!
let days = ["Sunday","Monday","Tuesday","Thursday","Friday","Saturday"]
// creates an array of 7 empty arrays
var tableData:Array = [[String]] (count: 7,repeatedValue:[])
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 addObjectToTable(sender: AnyObject) {
if(textField.text != "")
{
print (days[dayPicker.selectedRowInComponent(0)])
print (textField.text!)
tableData[dayPicker.selectedRowInComponent(0)].append(textField.text!); // Error: Cannot subscript a value of type 'Array'
textField.text = ""
tableView.reloadData()
}
}
}
Thanks!
I just remembered I ran into this problem a few times when I went back to some old projects that were a bit outdated. For me the fix was simply to change, in your example,
var tableData:Array = [[String]]
to
var tableData = [[String]]
If you are sure that the tableview will contain only days try to typecast the objects Array of AnyObject to Array of String. then use it.
var day= self.objects![indexPath.row] as! String
I working on a Swift app that uses a UIStepper , for user to enter a quantity into textField, how can I take the quantity and multiply by value stored in var?
Here is what I have so far
var value1 = 4 // value to multiply //
#IBOutlet weak var oneValue : UITextField!
#IBOutlet weak var oneClicker: UIStepper!
#IBOutlet weak var totalTextField: UITextField! // show total value1 * oneValue //
#IBAction func oneClicker(sender: UIStepper) {
// puts quantity into oneValue textField //
self.oneValue.text = Int(sender.value).description
}
#IBAction func calculateButton(sender: UIButton) {
// just can't figure out method? //
}
//Thanks for help//
#IBAction func calculateButton(sender: UIButton) {
println("\(calculate(self.oneValue.text.toInt()!)")
}
func calculate(value: Int) -> Float {
return Float(value * value1)
}
There you go.