import UIKit
class ViewController: UIViewController {
#IBOutlet weak var yearTextField: UITextField!
#IBOutlet weak var monthTextField: UITextField!
#IBOutlet weak var dayTextField: UITextField!
#IBOutlet weak var messageLabel: UILabel!
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 daysButtonPressed(sender: AnyObject) {
messageLabel.text = "The button is pressed!"
var dateComponets = NSDateComponents()
dateComponets.day = 2
dateComponets.month = 10
dateComponets.year = 1999
var calendar = NSCalendar(identifier: NSGregorianCalendar )
var birthDate = calendar?.dateFromComponents(dateComponets)
var currentDate = NSDate.date()
}
}
I was compiling the code and suddenly it shows me this error: date()' is unavailable: use object construction 'NSDate()' and also it shows me another error thats is: " 'NSCalendar?' does not have a member named 'dateFromComponents' " anyone can help me please!! I am new at swift and also to stack overflow
Use NSDate() instead of NSDate.date().
replace the ? after calendar with !.
calendar!.dateFromComponents(dateComponets)
Krys's suggestions were correct but also you left out some characters that will give you an issue
var dateComponets = NSDateComponents()
Should be:
var dateComponents = NSDateComponents()
Same with
var birthDate = calendar?.dateFromComponents(dateComponets)
Should be
var birthDate = calendar?.dateFromComponents(dateComponents)
Related
So i recently tried to create a very simple calcylator in xcode, the problem i have is when i press the calculate button when there is no numbers there the app crashes, and when i put anything that isnt a number there and press the calculate button it also crash, and i know it crash cause it cant convert nothing/non numbers into a double, but how do i check if it is numbers in the textfields and if it is it will show the result off the
equation and if there is no number it will just set the textfeilds to nothing
(faktor1.text = "") (faktor2.text = "") ...
well it looks like this right now (ränka ut means calculate)
here is the code i used,
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faktor1: UITextField!
#IBOutlet weak var faktor2: UITextField!
#IBOutlet weak var result: UILabel!
#IBOutlet weak var calculatebutton: UIButton!
#IBOutlet weak var clearui: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
result.text = ""
calculatebutton.layer.cornerRadius = 25.0
result.layer.cornerRadius = 25.0
clearui.layer.cornerRadius = 25.0
}
#IBAction func calculate( sender: Any) {
let input1 = Double(faktor1.text!)!
let input2 = Double(faktor2.text!)!
let calculation = input1 * input2
result.text = "(calculation)"
}
#IBAction func clearfnc( sender: Any) {
result.text = ""
faktor1.text = ""
faktor2.text = ""
}
}
You can simply unwrap your optionals the Swift way, instead of using ! (force unwrap)
This is an example using guard:
#IBAction func calculate(sender: Any) {
guard
let input1String = faktor1.text,
let input2String = faktor1.text,
let input1 = Double(input1String),
let input2 = Double(input2String)
else {
faktor1.text = ""
faktor1.text = ""
return
}
let calculation = input1 * input2
result.text = "\(calculation)"
}
I am trying to create an app that can help you calculate sales tax on an item. Of course the app requires multiplication But I keep encountering the error:
"Type of expression is ambiguous without more context"
Can you help me? I'm new to swift so also try to explain why I am incorrect. This is my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Tax: UITextField!
#IBOutlet weak var Answer: UITextField!
#IBAction func Calculate(_ sender: Any) {
let a = Item.text
let conversionRate = Tax
let b = Int(a!)! * conversionRate
Answer.text = ("\(b)")
}
}
Thanks!!
Your primary issue is your attempt to multiply an Int and a UITextField.
You attempt to create an Int from Item.text but you make no similar attempt to convert Tax.text to a number.
There are also many other issues with your code. You are using the ! operator too much and your app will crash as a result.
And your naming conventions need to be improved. Variables and methods should start with lowercase letters.
Here's your code as it should be written:
class ViewController: UIViewController {
#IBOutlet weak var item: UITextField!
#IBOutlet weak var tax: UITextField!
#IBOutlet weak var answer: UITextField!
#IBAction func calculate(_ sender: Any) {
if let itemStr = item.text, let taxStr = tax.text, let itemVal = Int(itemStr), let taxVal = Int(taxStr) {
let result = itemVal * texVal
answer.text = "\(result)"
} else {
answer.text = "Invalid values"
}
}
}
You're trying to multiply a variable of UITextField type with a variable of Int. Try this:
class ViewController: UIViewController {
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Tax: UITextField!
#IBOutlet weak var Answer: UITextField!
#IBAction func Calculate(_ sender: Any) {
guard let a = Int(Item.text ?? "0") else { return }
guard let conversionRate = Int(Tax.text ?? "0") else { return }
let b = a * conversionRate
Answer.text = ("\(b)")
}
}
I'm really new to Swift and I am having problems with the conversion of a string (entered in a text field) to an integer.
I'm trying to create a small calculation app (I was following a tutorial on YouTube but it's old).
My app has 3 text fields, a label (that is meant to display the result), and a button to start the calculation.
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var valueA: UITextField!
#IBOutlet weak var valueB: UITextField!
#IBOutlet weak var valueC: UITextField!
#IBOutlet weak var result: UILabel!
#IBAction func calculateTotal(_ sender: Any) {
var a:Int? = Int(valueA.text)
var b:Int? = Int(valueB.text)
var c:Int? = Int(valueC.text)
var answer = a! * b! * c!
}
}
Try this (crash free code and you can add n number of textfield/string values as a number string):
var arrayOfTextFieldValues = [valueA.text, valueB.text, valueC.text]
#IBAction func calculateTotal(_ sender: Any) {
if let multiplication = multiplication(arrayString: arrayOfTextFieldValues) {
print("Answer = \(multiplication)")
result.text = "\(multiplication)"
}
}
// handle operations
func multiplication(arrayString: [String?]) -> Int? {
var answer:Int?
for arrayElement in arrayString {
if let stringValue = arrayElement, let intValue = Int(stringValue) {
answer = (answer ?? 1) * intValue
}
}
return answer
}
I am able to save an integer and load it using NSUserdeafaults but when I load up the number and try to continue adding to that number it starts at 0.
Example: I press the button 7 times and switch to a different page. I go back and click load button and it days 7. When I click it again it says 1.
Here is my "press for money" code:
//Press for Money
#IBAction func MoneyPress(sender: AnyObject) {
Money += 1
var MoneyNumberString:String = String(format: "Dollars:%i", Money)
self.DollarsLabel.text = (string: MoneyNumberString)
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize()
}
Loading Code:
#IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
}
Please help if you know how to make it continue adding to that number.
Full Code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var MoneyButton: UIButton!
#IBOutlet weak var OptionButton: UIButton!
#IBOutlet weak var FeelingLuckyButton: UIButton!
#IBOutlet weak var TrophiesButton: UIButton!
#IBOutlet weak var DollarsLabel: UILabel!
#IBOutlet weak var BuyNowOne: UIButton!
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.
}
var Money = Int(0)
//Press for Money
#IBAction func MoneyPress(sender: AnyObject) {
Money += 1
var MoneyNumberString:String = String(format: "Dollars:%i", Money)
self.DollarsLabel.text = (string: MoneyNumberString)
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize()
}
#IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
}
}
The problem is that you're setting Money to 0 when you actually want to set it to contain the value in your NSUserDefaults. To do that in your LoadTestButton method, try this:
#IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
// Set "Money" to contain the numbers in your "money"
// string converted to an Int
Money = money!.stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).toInt()!
}
I've been working on a Swift tutorial.
In the tutorial the authors neglected to explain how to dismiss the keyboard on the simulator.
I tried the standard method that I'm aware of; resignFirstResponder( )
However I keep getting an error; cannot convert a string into a bool.
I haven't been able to find a workable answer on Stack overflow to date.
Any ideas?
I've included the code below.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var yearTextField: UITextField!
#IBOutlet weak var dayTextField: UITextField!
#IBOutlet weak var monthTextField: UITextField!
#IBOutlet weak var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.yearTextField.delegate = self
self.dayTextField.delegate = self
self.monthTextField.delegate = self
}
// Suggested fix not working?
// func textFieldShouldReturn(textField: UITextField!) -> Bool {
// textField.resignFirstResponder()
// return true;
// }
#IBAction func daysButtonPressed(sender: AnyObject) {
println("Days Button Pressed")
messageLabel.text = "Button pressed"
messageLabel.resignFirstResponder()
var dateComponents = NSDateComponents()
dateComponents.day = dayTextField.text.toInt()! // 28
dateComponents.month = monthTextField.text.toInt()! // 3
dateComponents.year = yearTextField.text.toInt()! // 1956
var calendar = NSCalendar(identifier: NSGregorianCalendar)
var birthDate = calendar.dateFromComponents(dateComponents) //NSDate
var currentDate = NSDate.date()
println(birthDate)
println("Current Date \(currentDate)")
var durationDateComponets = calendar.components(NSCalendarUnit.CalendarUnitDay,
fromDate: birthDate!,
toDate: currentDate,
options: nil)
var numberOfDaysAlive = durationDateComponets.day
//Format with commas
var numberFormatter = NSNumberFormatter()
numberFormatter.usesGroupingSeparator = true
var dayString = numberFormatter.stringFromNumber(numberOfDaysAlive)
messageLabel.text = "Days alive: \(dayString)"
// self.messageLabel.resignFirstResponder()
}
}
The keyboard is up because one of your UITextField's is the first responder. Since you don't know which one, call resignFirstResponder() on each of them.
In daysButtonPressed() instead of calling:
messageLabel.resignFirstResponder()
You need to call:
dayTextField.resignFirstResponder()
monthTextField.resignFirstResponder()
yearTextField.resignFirstResponder()