NSPopUpButton selection to Float Swift 4 - swift

I am trying to get a String value to a Float value from a NSPopUpButton.
E.g. I have 3 number selections. 50, 20, 10. When the user selects one of the numbers I would like a calculation made into a Float value.
I know this may be something very simple but I am new and I can't find anything on Stackoverflow. Any help would be appreciated. Here is an example of the code I have.
#IBOutlet weak var userInput: NSTextField!
#IBOutlet weak var result: NSTextField!
#IBOutlet weak var userMenuSelection: NSPopUpButton!
override func viewDidLoad() {
super.viewDidLoad()
userMenuSelection.removeAllItems()
userMenuSelection.addItems(withTitles: ["50", "20", "10"])
}
#IBAction func pushButtonforResult(_ sender: Any) {
/*
Not sure how to take the selected userMenuSelection and multiply it by the users input to get my result in a float.
E.g. look below. This of course does not work because the menu items are strings.
*/
result.floatValue = userMenuSelection * userInput.floatValue
}
Hope this makes sense to what I am asking.

As you see, your userMenuSelection has titles representing the Float values as String.
You can simply retrieve the selected title and convert it to Float:
#IBAction func pushButtonforResult(_ sender: Any) {
var selectedValue = Float(userMenuSelection.titleOfSelectedItem ?? "0") ?? 0.0
result.floatValue = selectedValue * userInput.floatValue
}

You can try
let arr = ["50", "20", "10"]
//
#IBAction func pushButtonforResult(_ sender: NSPopUpButton) {
let selectedValue = Float(arr[sender.selectedTag()])!
Result.floatValue = selectedValue * userInput.floatValue
// OR
let selectedValue = Float(sender.selectedItem!.title)!
result.floatValue = selectedValue * userInput.floatValue
}

Related

using String with UIStepper - Swift

i have a label and a UIStepper, i need to increase the number of that label without lossing the letters ( Kd ) . my label will be like this "5.000 Kd" and when i increase the number i don't want to loss the ( Kd ) label.
this is my code
import UIKit
import GMStepper
class ViewController: UIViewController {
#IBOutlet var stepper: GMStepper!
#IBOutlet var price: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func stepper(_ sender: Any) {
let label = "5.000 Kd" as NSString
price.text! = String(label.doubleValue * stepper.value)
}
}
If you are hard-coding the string contents of the label, just maintain a numeric value and rebuild the label contents each time that value changes:
class ViewController: UIViewController {
#IBOutlet var stepper: GMStepper!
#IBOutlet var priceLabel: UILabel!
var price: Double = 5.0
#IBAction func stepper(_ sender: Any) {
let newValue = price * stepper.value
//Format the price with 3 decimal places
let priceString = String(format: "%.3f", newValue)
Construct a string with the formatted price and " Kd" and put it in the label
priceLabel.text = "\(priceString) Kd")
}
}
Consider using NumberFormatter to format currency:
let cf = NumberFormatter()
cf.currencyCode = "KWD"
cf.numberStyle = .currency
cf.string(from: 5000)
That respects the user's Locale.

Swift/Xcode: trying to access local variable that gets updated in another function

I'm a beginner and I am struggling with a certain problem regarding local variables. Specifically, I am trying to make an app where I test certain fraction questions. So, I need to generate random numbers for the test and access them so that the checker function can make sure the user got the right answer. However, if I generate a new set of numbers when the user clicks "ask question", the other checker function doesn't know what those numbers are... Here is my code below:
class ViewControllerEasy: UIViewController {
#IBOutlet weak var giveQuestionOutlet: UIButton!
#IBOutlet weak var nextButtonOutlet: UIButton!
#IBAction func nextQuestionButton(_ sender: Any) {
nextButtonOutlet.isHidden = true
giveQuestionOutlet.isEnabled = true
easyQuestionResponse.text = ""
easyQuestionLabel.text = ""
resultLabel.text = ""
}
#IBOutlet weak var easyQuestionResponse: UITextField!
#IBOutlet weak var easyQuestionLabel: UILabel!
#IBAction func easyQuestionButton(_ sender: Any) {
let num1 = Int.random(in: 1 ..< 6)
let num2 = Int.random(in: 2 ..< 11)
easyQuestionLabel.text = "What percentage does \(num1) / \(num2) represent? (Round down to the closest whole number)"
}
#IBOutlet weak var resultLabel: UILabel!
#IBAction func checkButton(_ sender: Any) {
let expectedAnswer = ((num1 * 100) / num2)
let expectedAnswer2 = Float(expectedAnswer)
if Float(easyQuestionResponse.text!) == round(expectedAnswer2) {
resultLabel.text = "Great Job! Correct Answer."
nextButtonOutlet.isHidden = false
giveQuestionOutlet.isEnabled = false
}else {
resultLabel.text = "Sorry, that is incorrect. The correct answer was: \(round(expectedAnswer2))%"
nextButtonOutlet.isHidden = false
giveQuestionOutlet.isEnabled = false
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
return string.rangeOfCharacter(from: invalidCharacters) == nil
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
So, how can I generate new questions when the user clicks the button to ask for it and also make sure that the code can check whether or not the user got the right answer? I tried looking at using a global variable, but that would keep the values same after the first execution of the random numbers call. Thus, I hope someone can help me with this problem. Thanks in advance.

How to access a text field value and convert to double

I am working on trying to build a tip calculator using swift but am running into a multitude of problems. I have a text box where the user enters in the bill amount and then they can adjust a slider to indicate the percentage that they want to tip. I have managed to get the slider and label associated with it to work where changing the value on the slider changes the label. However, I can't figure out how to get the text field to work. I attempted to create an action for the bill amount text box being changed but no matter what I put in it, it doesn't seem like the code is ever being executed (Whenever I run the code and click in the text box, the keyboard won't go away so maybe this is part of the problem?). All that I need is to be able to access the value in the text box field inside of my action when I click the calculate button but I can't seem to even get the value to show up much less convert it to a double so I can perform calculations on it. I am super new to swift and really want to learn what I am doing wrong. I have tried multiple tutorials and similar questions on here but none of them work. I appreciate all help y'all can give.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtBillAmount: UITextField!
#IBOutlet weak var lblTipPercentage: UILabel!
#IBOutlet weak var sldTipPercentage: UISlider!
#IBOutlet weak var lblTipAmount: UILabel!
#IBOutlet weak var lblTotalAmount: UILabel!
var tipPercentage = 10
var billAmount = ""
#IBAction func valueChanged(sender: AnyObject) {
let currentValue = Int(sldTipPercentage.value)
lblTipPercentage.text = "\(currentValue)%"
tipPercentage = currentValue
}
#IBAction func btnCalculate(sender: AnyObject) {
lblTipAmount.text = "\(billAmount)"
}
#IBAction func txtBillAmountValueChanged(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
//txtBillAmount.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func btnReset(sender: UIButton) {
sldTipPercentage.value = 10
lblTipPercentage.text = "10%"
txtBillAmount.text = ""
lblTipAmount.text = "--"
lblTotalAmount.text = "--"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is a screenshot of how the UI looks
Error that I am getting
[Xcode >= 7 and Swift > 2]
Try like this
#IBAction func btnCalculate(sender: AnyObject) {
if let textValue = txtBillAmount.text {
let billAmnt = Double(textValue)
let tipAmount = (billAmnt*tipPercentage)/100
lblTipAmount.text = "\(tipAmount)"
}
}
If you are using Xcode-6 and Swift < 2 then try the following way. because String initializer for Double is only available in Swift 2 (Xcode 7). [Recommend update your Xcode]
#IBAction func btnCalculate(sender: AnyObject) {
let billAmnt = (txtBillAmount.text! as NSString).doubleValue
let tipAmount = (billAmnt*tipPercentage)/100
lblTipAmount.text = "\(tipAmount)"
}

Having Problems calculating the volume with 3 input values.

i'm a fairly new programmer and i've just started on Xcode. Atm i am trying to make a calculator that can calculate the total volume from 3 input values (Height, length & width) but i can't seem to make it calculate it. right now i am able to enter a value and click the button and then it crashes.
Thanks in advance!
here is my code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBOutlet weak var HeightInput: NSTextField!
#IBOutlet weak var LengthInput: NSTextField!
#IBOutlet weak var WidthInput: NSTextField!
#IBOutlet weak var Result: NSTextField!
#IBAction func Calculate(_ sender: Any) {
var height = Int(HeightInput.stringValue)
var width = Int(WidthInput.stringValue)
var length = Int(LengthInput.stringValue)
if height == 0
{
Result.stringValue = "Error"
}
else{
var result = width! * height! * length!
Result.stringValue = "the volume is: \(result)"
}
}
Try something like this.
#IBAction func Calculate(_ sender: Any) {
let height = Int(HeightInput.stringValue) ?? 0
let width = Int(WidthInput.stringValue) ?? 0
let length = Int(LengthInput.stringValue) ?? 0
let result = height * width * length
if result == 0 {
Result.stringValue = "Error"
else {
Result.stringValue = "The volume is: \(result)"
}
}
When converting your label value to an integer, it will return an optional (meaning it could be nil). When you are calculating your result, you are force-unwrapping these optionals with the !.
I recommend conditionally unwrapping these values. Using ?? meaning that if the value is nil, it will default to whatever you put after the ??.

Multiply a UI text field with number - Swift

Just starting learning swift but stuck when trying to multiply an input with another number and display on a label. I get the error that the number isn't a string and tried to cast but didn't work.
class ViewController: UIViewController {
#IBOutlet weak var entry: UITextField!
#IBOutlet weak var answer: UILabel!
#IBAction func button(_ sender: Any) {
answer.text = entry.text * 2
}
}
You should cast the text into a Double, an Int etc., then convert the calculation to a string.
if let entry = Double(entry.text) {
answer.text = "\(entry * 2)"
}
or
if let entry = Int(entry.text) {
answer.text = "\(entry * 2)"
}
If you know that the entry will hold a number
answer.text = String(Int(entry.text)! * 2)
Using optional unwrapping instead
if let num = Int(entry.text) {
answer.text = String(num * 2)
}