I want to create a simple BMI calculator using height and weight and I am having trouble converting my UITextField strings to integers for the calculation.
Here's my working code:
import UIKit
class BMICalculator: UIViewController {
//MARK: Properties
#IBOutlet weak var weightField: UITextField!
#IBOutlet weak var heightField: UITextField!
#IBOutlet weak var solutionTextField: UILabel!
#IBAction func calcButton(_ sender: AnyObject) {
let weightInt = Int(weightField)
let heightInt = Int(heightField)
solutionTextField.text = weightInt/(heightInt*heightInt)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Anyone have any ideas? I tried searching for the solution but couldn't find anything specific to this issue.
Use this:
guard let text1 = weightField.text else {
return
}
guard let text2 = heightField.text else {
return
}
guard let weightInt = Int(text1) else {
return
}
guard let heightInt = Int(text2) else {
return
}
solutionTextField.text = weightInt /(heightInt*heightInt)
//Change your name for this outlet 'solutionTextField' to 'solutionLabel' since it is a UILabel not UITextField
The TextField only accepts a String, it wont take an Int.
Change this:
solutionTextField.text = weightInt/(heightInt*heightInt)
To this:
solutionTextField.text = String(weightInt/(heightInt*heightInt))
I don't think your code is working. To get the values out of your UITextFields and convert them to Ints, you'll need to pull them out of the '.text properties. Then, when you calculate the result, you'll need to convert it back to a string and set solutionTextField?.text equal to that result.
class BMICalculator: UIViewController {
//MARK: Properties
#IBOutlet weak var weightField: UITextField!
#IBOutlet weak var heightField: UITextField!
#IBOutlet weak var solutionTextField: UILabel!
#IBAction func calcButton(_ sender: AnyObject) {
let weightInt = Int((weightField?.text!)!)
let heightInt = Int((heightField?.text!)!)
let solution = weightInt!/(heightInt!*heightInt!)
solutionTextField?.text = "\(solution)"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Keep in mind that this code is very dangerous because you're not safely unwrapping optionals, but that's a different thread.
Hope this helps.
Related
As the title says, I want to count the words in a string, which is filled by the user. For that purpose, I will simplify it a little and I will count the white spaces in the string, store the value in an other variable and the print that new variable.
The code I am using is the following:
import UIKit
class TransViewController: UIViewController {
#IBOutlet var trad_text: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
trad_text!.layer.borderWidth = 1
trad_text!.layer.cornerRadius = 20
trad_text!.layer.borderColor = UIColor(red:0.22, green:0.26, blue:0.39, alpha:1.0).cgColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
let text = trad_text.text
let num_words = text?.characters.split(separator: " ").map(String.init)
print(num_words)
// Dispose of any resources that can be recreated.
}
But it does not print any number of words. Can someone find why this code gives the error?
Thank you for your time
You can use this code:
var string = "first second third"
let count = string.components(separatedBy: .whitespaces).count
Count equal 3 for this case.
I finally did it with the following code, maybe it will be useful to someone:
import UIKit
import Foundation
class TransViewController: UIViewController {
final class Shared {
static let shared = Shared() //lazy init, and it only runs once
var stringValue : String!
var num_words : Int!
var boolValue : Bool!
}
#IBOutlet var trad_text: UITextView!
#IBOutlet var buttonTrad: UIButton!
#IBOutlet var labelsitoh: UILabel!
#IBAction func butCalc(_ sender: AnyObject) {
let text = trad_text.text
let num_words = (text?.components(separatedBy: " ").count)!-1
Shared.shared.num_words = num_words
}
override func viewDidLoad() {
super.viewDidLoad()
trad_text!.layer.borderWidth = 1
trad_text!.layer.cornerRadius = 20
trad_text!.layer.borderColor = UIColor(red:0.22, green:0.26, blue:0.39, alpha:1.0).cgColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
I'm very new to all of this and I found some code that got me understanding some of this syntax. I'm trying to create a textfield that lets me type in a value that updates the stepper's value. The stepper currently works (updates the uitextfield) but when I change the value in the textfield it doesn't update the stepper's value, so when I click on the stepper, it reverts back to whatever value it was before I typed in a value... Can anyone tell me why the two functions STracksValueDidChange and CTrackValueDidChange have errors?
Here's my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var STracks: UITextField!
#IBOutlet weak var STracksStepper: UIStepper!
#IBOutlet weak var CTracks: UITextField!
#IBOutlet weak var CTrackStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
STracksStepper.autorepeat = true
STracksStepper.maximumValue = 100.0
STracksStepper.minimumValue = 2.0
STracksStepper.stepValue = 2.0
print(STracksStepper.value)
STracks.text = "\(Int(STracksStepper.value))"
STracksStepper.addTarget(self, action: "SstepperValueDidChange:", forControlEvents: .ValueChanged)
STracks.addTarget(self, action: "STextValueDidChange:", forControlEvents: .ValueChanged)
CTrackStepper.autorepeat = true
CTrackStepper.maximumValue = 100.0
CTrackStepper.minimumValue = 2.0
CTrackStepper.stepValue = 2.0
print(CTrackStepper.value)
CTracks.text = "\(Int(CTrackStepper.value))"
CTrackStepper.addTarget(self, action: "CstepperValueDidChange:", forControlEvents: .ValueChanged)
CTracks.addTarget(self, action: "CTextValueDidChange:", forControlEvents: .ValueChanged)
}
//Steppers will update UITextFields
func SstepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UITextField] = [STracksStepper: STracks]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}
func STracksValueDidChange(SText: UITextField) {
let STextMapping: [UITextField: UIStepper] = [STracks: STracksStepper]
STextMapping[SText]!.value = "(SText.text)"
}
func CstepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UITextField] = [CTrackStepper: CTracks]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}
func CTrackValueDidChange(CText: UITextField) {
let CTextMapping: [UITextField: UIStepper] = [CTracks: CTrackStepper]
CTextMapping[CText]!.value = "(CText.text)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Try something like this.
CTrackStepper.value = Double(Textfield.text)
I am not so sure what the mapping is in your code.
But i don't think you need it for changing the value.
Update, made a project my self:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textfield: UITextField!
#IBOutlet weak var stepper: UIStepper!
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 stepperValueChanged(sender: UIStepper) {
textfield.text = String(sender.value)
}
#IBAction func valueChanged(sender: UITextField) {
if Double(sender.text!) != nil {
stepper.value = Double(sender.text!)!
}
}
}
For steppervaluechanged and valuechanged just drag from uistepper and textfield and choose action and change the Anyobject to Uistepper of Uitextfield.
Good luck :)
I've done plenty of searching but am not finding the answer to my question.
My two UITextFields fields are resetting using the clear function. The UILabel retains the original value from the printWatts function, doesn't clear. Would appreciate any advice to resolve this small issue as I learn Swift. Thanks!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var inputFeet: UITextField!
#IBOutlet weak var inputWatts: UITextField!
#IBOutlet weak var resultsLabel: UILabel!
var stripFeet = ""
var wattValue = ""
var totalWatts : Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func submitButton(sender: AnyObject) {
calculateWatts()
}
#IBAction func clearButton(sender: AnyObject) {
clear()
}
func calculateWatts() {
if let stripFeet = inputFeet.text,
wattValue = inputWatts.text,
fstripFeet = Float(stripFeet),
fwattValue = Float(wattValue){
totalWatts = fstripFeet * fwattValue
}
printWatts()
}
func printWatts() {
let formatWatts = String(format: "%0.2f", totalWatts)
resultsLabel.text = "Total watts: \(formatWatts)"
}
func clear(){
inputFeet.text = ""
inputWatts.text = ""
self.resultsLabel.text = ""
}
}
Thanks to #Eendje for suggesting that I check my connections. I had the submit and clear actions both connected to my submit button. Option drag is too convenient. All good now.
So recently I have been making a practice app that has a textfield and a label. When you enter something into the textfield and hit save it should change the label to that text and save it. The reason why it saves is so when you open the app the text of the label is equal to the last thing you saved. The text will save again if you hit save on a new string in the text box.
The problem I am having is that the label won't appear with text until you save something new and the string isn't saving so their is nothing there even if you saved something.
Here is my code from the ViewController.swift:
//
// ViewController.swift
// Help
//
// Created by Lucas on 9/30/15.
// Copyright (c) 2015 Lucas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
var current = ""
var Saved = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = Saved
if(currentDefault.valueForKey("Saved") != nil)
{
self.Saved = currentDefault.valueForKey("Saved") as! NSString! as String
}
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Set(sender: AnyObject) {
setall()
}
func setall()
{
current = Textfield.text!
Label.text = Textfield.text!
let currentDefault = NSUserDefaults.standardUserDefaults()
Saved = (currentDefault.valueForKey("saved") as? String)!
currentDefault.setValue(Saved, forKey: "saved")
Savedlbl.text = Textfield.text
currentDefault.synchronize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Here is where I think the problem is in the view did load that would make sense. When the app loads its not setting it to the last thing saved.
import UIKit
class ViewController: UIViewController {
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
var current = ""
var Saved = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = Saved
if(currentDefault.valueForKey("Saved") != nil)
{
self.Saved = currentDefault.valueForKey("Saved") as! NSString! as String
}
// Do any additional setup after loading the view, typically from a nib.
}
Thanks and let me know if you need any more info, I will provide it as fast as I can!
Don't use valueForKey/setValue:forKey:. Those are KVC methods. You want setObject:forKey: and objectForKey:.
Your problems are that you are doing things in the wrong order. In viewDidLoad you are setting the textfield before you have retrieved the value from user defaults and in setall you are re-saving the previously saved value, not the new value.
Try:
import UIKit
class ViewController: UIViewController {
var saved=""
var current=""
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
self.saved=currentDefault.stringForKey("Saved") ?? ""
self.Savedlbl.text=self.saved
}
#IBAction func Set(sender: AnyObject) {
setall()
}
func setall() {
self.current = self.Textfield.text!
self.Label.text = self.current
let currentDefault = NSUserDefaults.standardUserDefaults()
currentDefault.setObject(self.current,forKey:"Saved")
self.Savedlbl.text = self.Textfield.text
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Also, by convention variables should start with a lower case letter and classes with an upper case. I changed Saved to saved and Current to current but I didn't change the IBOutlets because you will need to remake the connection in IB for those, but you should.
When I create an IBaction for a button I can easily get it to perform an action for example:
#IBAction func click(sender: AnyObject) {
label6.hidden = false}
How do I get it to execute a totally different task when it is clicked for a second or third time etc?
Thanks
EDIT: When I try this I get an error "Viewcontroller.type does not have a member named "label1", this also is stated for "label2" Any ideas why as I have already added the label in as an outlet. Do I need to declare it somewhere else to get it to work? Thanks
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
label1.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
class MyButtonClass
{
var clickCounter: Int = 0
#IBAction func click(sender: AnyObject)
{
clickCounter += 1
if (clickCounter == 1)
{label1.text = "text1"}
else if (clickCounter == 2)
{label2.text = "text1"
clickCounter = 0}
}
}
}
Replace your code with the following:
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
label1.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
var clickCounter: Int = 0
#IBAction func click(sender: AnyObject)
{
clickCounter += 1
if (clickCounter == 1)
{
label1.text = "text1"
}
else if (clickCounter == 2)
{
label2.text = "text1"
clickCounter = 0
}
}
}
You can have a counter and depending on its value fire another method from the one called on click
Create a property that counts the tap count
Increment the tap count on each click
Implement a switch on the tap count to perform different actions (IBAction acts as a dispatcher)