why Xcode didn't make addition? - swift

I use gm stepper in my app and , it corresponding to labels. I have 4 different labels and one additional label for addition to values . The labels which corresponding to GM Steppers working well but ı stumble in addition values of labels.
class ViewController: UIViewController {
#IBAction func gmstp1(_ sender: GMStepper) {
label1.text = String(sender.value*1.5)
label6.text = String(sender.value)
}
#IBOutlet weak var label1: UILabel!
#IBAction func gmstp2(_ sender: GMStepper) {
label2.text = String(sender.value*0.89)
}
#IBOutlet weak var label2: UILabel!
#IBAction func gmstp3(_ sender: GMStepper) {
label3.text = String(sender.value*26)
}
#IBOutlet weak var label3: UILabel!
#IBAction func gmstp4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
}
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
My question about ; Is there any solution without using buttons? Could you handle that?
*Label5 using for summary.

Simply because, unlike a GMStepper, a UILabel doesn't have a value property. So you'll have to get the text string in each label, convert it to a Double, and then add them up:
if let text1 = label1.text, let value1 = Double(text1),
let text2 = label2.text, let value2 = Double(text2),
let text3 = label3.text, let value3 = Double(text3),
let text4 = label4.text, let value4 = Double(text4) {
let sum = value1 + value2 + value3 + value4
label5.text = String(sum)
}

Related

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

pass data from tableviewcontroller to another tableviewcontroller in swift

I have a form I am creating
this form gets filled with textfields the user inputs. After answering all the questions a button pops up to save.
I am having a problem making this tableviewcontroller to pass the data to a new tableviewcontroller. I'm stuck and not sure how to go about this.
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var firstNameField: UITextField!
#IBOutlet var middleNameField: UITextField!
#IBOutlet weak var lastNameField: UITextField!
#IBOutlet weak var addressField: UITextField!
#IBOutlet weak var aptNumField: UITextField!
#IBOutlet weak var cityField: UITextField!
#IBOutlet weak var stateField: UITextField!
#IBOutlet weak var zipField: UITextField!
#IBOutlet weak var phoneOneField: UITextField!
#IBOutlet weak var phoneTwoField: UITextField!
#IBOutlet weak var allergiesField: UITextField!
#IBOutlet weak var DobField: UILabel!
#IBOutlet weak var sexField: UILabel!
#IBOutlet weak var hospitalField: UITextField!
#IBOutlet weak var doctorField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Notifications to push datepicker
NotificationCenter.default.addObserver(forName: .saveDateTime, object: nil, queue: OperationQueue.main) { (notification) in
let dateVc = notification.object as! DatePopupViewController
self.DobField.text = dateVc.formattedDate
}
//Notifications to push genderpicker
NotificationCenter.default.addObserver(forName: .saveGender, object: nil, queue: OperationQueue.main) { (notification) in
let genderVc = notification.object as! GenderPopupViewController
self.sexField.text = genderVc.selectedGender
}
updateWidthsForLabels(labels: labels)
}
//Save Button Function
func textFieldDidChange(_ textField: UITextField) {
if textField == firstNameField || textField == lastNameField || textField == middleNameField || textField == addressField || textField == lastNameField || textField == cityField || textField == cityField || textField == stateField || textField == zipField || textField == phoneOneField || textField == phoneTwoField || textField == allergiesField {
saveBtn.isHidden = true
} else {
saveBtn.isHidden = false
}
}
#IBAction func saveBtnPressed(_ sender: Any) {
performSegue(withIdentifier: "saveFirstPageSegue", sender: self)
}
}
what about starting creating a model:
Form.swift
struct Form {
var firstname: String?
var middlename: String?
....
var doctor: String?
init(firstname: String, middlename: String, ..., doctor: String) {
self.firstname = firstname
self.middlename = middlename
...
self.doctor = doctor
}
}
now you can create this form instance when saving and pushing the data to the new VC:
yourCurrentForm.swift
#IBAction func saveBtnPressed(_ sender: Any) {
let formData = Form(firstname: firstNameField.text, middlename: middleNameField.text, ..., doctor: doctorField.text)
let newVC = myNewViewController()
newVC.form = formData
self.navigationController?.pushViewController(newVC, animated: true)
}
NewViewController.swift
class myNewViewController: UIViewController {
var form: Form?
.....
}
UPDATE:
Here is the repo: https://github.com/FlorianLdt/LFEasyDelegate
If you have some question just ask me
Hope it helps.
First Option - Structs - Preferred
Make use of Structs :
struct Manager
{
static var value : String = ""
}
Noe Update value of that function by just calling
Manager.value = "newValue"
Access that value anywhere Assign it to other Variables
let newStr : String = Manager.value
Second Option - AppDelegate - Not ideal
Create new object in AppDelegate
Now create a new object to access appDelegate
let appDel = UIApplication.shared.delegate as! AppDelegate
Access Value and update as below
appDel.Frequency = 1.0
Third Option - NSObjectClass
Create a new NSObject class as below
//Instance created when NSObject class is first time loaded in memory stack
static let shared = wrapperClass()
//Create a value to access Globally in Object class
var newValueInClass : String = ""
Now time to access that created Object
wrapperClass.shared.newValueInClass = "iosGeek"
Now Anywhere write this Line
print(wrapperClass.shared.newValueInClass)
Console Output
Better to use struct classes to manage data globally

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

How to use UIStepper to put integer in to a text field with swift

How Can I use Swift to put integer in textfield from UIStepper?
this is how I did it in Objective C:
- (IBAction)oneClicker:(UIStepper *)sender {
self.oneValue.text = [NSString stringWithFormat:#"%d",
[[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue]];
AudioServicesPlaySystemSound(_PlaySound);
}
It's simple
#IBOutlet weak var oneValue: UITextField!
#IBAction func oneClicker(sender: UIStepper) {
self.oneValue.text = Int(sender.value).description
}
Here is how I got it to work don't know if the best way but here it is
#IBOutlet weak var oneClicker: UIStepper!
#IBAction func oneClicker(sender: UIStepper) {
oneValue.text = "\(Int(oneClicker.value))"
}
While trying above, got an error. Tried something different and it worked.
#IBOutlet var quantity: UILabel!
#IBOutlet var StepCounter: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
StepCounter.autorepeat = true
StepCounter.maximumValue = 10.0
StepCounter.minimumValue = 1.0
println(StepCounter.value)
quantity.text = "\(Int(StepCounter.value))"
StepCounter.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
}
func stepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UILabel] = [StepCounter: quantity]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}

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

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.