Swift how to multiply value of quantity put in textfield with UIStepper - swift

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.

Related

UITableview data is changing when I scroll

I have made this protocol in my cell class
protocol CellDelegate: AnyObject{
func plusButton(tag: Int)
func minusButton(tag: Int)
}
class CartTableViewCell: UITableViewCell {
#IBOutlet weak var plusButton: UIButton!
#IBOutlet weak var minusButton: UIButton!
#IBOutlet weak var itemsCountLabel: UILabel!
weak var delegate: CellDelegate?
var count = 0
var totalAmount = 0.0
var modelPrice:Double = 0.0
override func awakeFromNib() {
super.awakeFromNib()
itemsCountLabel.text = String(count)
}
#IBAction func addButton(_ sender: Any) {
delegate?.plusButton(tag: (sender as AnyObject).tag)
count += 1
totalAmount = modelPrice * Double(count)
itemsCountLabel.text = String(count)
}
#IBAction func minusButton(_ sender: Any) {
delegate?.minusButton(tag: (sender as AnyObject).tag)
if count > 0{
count -= 1
totalAmount = modelPrice * Double(count)
it emsCountLabel.text = String(count)
print(totalAmount)
}
}
}
this is the code I have placed in my cellForRowat method in my viewcontroller
cell.delegate = self
cell.plusButton.tag = indexPath.row
and added this extension
extension ViewController: CellDelegate{
func plusbutton(tag: Int)
func minusButton(tag:Int)}
When I tap on plus button my countLabel is incremented and vise versa. The issue is when I scroll the tableView my values are shuffled(not same). What is the reason and how to solve this.
If I understand your code you modify the value of count in the cell. Do you modify it in your model in the cell delegate aka controller ? I so you need to keep coherency in your cell by either updating the label in the cell or either reload the cell in the cell delegate.

Swift: Tracking User's score

I'm trying to create a Quiz app that consists of two buttons, false and true button. My question is, as I answer more questions in the app, I want the textLabel to keep track of my score. And then when I circle back to the first question again, it should reset. This is my code so far. I'm looking forward to your answers.
class ViewController: UIViewController {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var progressBar: UIProgressView!
#IBOutlet weak var trueButton: UIButton!
#IBOutlet weak var falseButton: UIButton!
#IBOutlet weak var scoreLabel: UILabel!
var quizBrain = QuizBrain()
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
progressBar.progress = 0.0
}
#IBAction func answerButtonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle
let userGotItRight = quizBrain.checkAnswer(userAnswer!)
if userGotItRight {
sender.shortChangeTo(.green)
} else {
sender.shortChangeTo(.red)
}
quizBrain.nextQuestion()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.updateUI()
}
}
func updateUI() {
questionLabel.text = quizBrain.getQuestionText()
trueButton.backgroundColor = UIColor.clear
falseButton.backgroundColor = UIColor.clear
progressBar.progress = 33
scoreLabel.text = "Score: \(quizBrain.getScore)"
}
}
You don't have any code for it yet? You can create a struct like user
struct user {
var score: Int = 0
mutating func answerRight (){
self.score =+ 1 }
mutating func reset (){
self.score = 0 }
}
But I see this in your code "Score: (quizBrain.getScore)"
This says that quizBrain should know the score. But you never add a value to it So check your quizBrain and create a function or an object that can track the score and then call it here "if userGotItRight {}"

unsure how to unwrap uilabel optional to calculate my to uilabels

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

Cannot convert value of type 'String?' to type 'NSString' in coercion

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

Swift - Multiply values from two UITextFeild's

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)")