I'm learning swift by building a basic counting app (based on this tutorial https://www.youtube.com/watch?v=3blma4PCRak) and I'm trying to have a function that counts on increments of 3 based on the state of a switch.
It seems a lot of the answers I find in tutorials online and from SO are from many years ago and a lot of the syntax is deprecated, including:
• instead of oddSwitch.On now it is oddSwitch.isOn
• Stating colors changed from UIColor.redColor to just UIColor.red
And so on...below is my code thus far:
//
// ViewController.swift
// TestApp
//
// Created by kawnah on 2/8/17.
// Copyright © 2017 kawnah. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var outputLabel: UILabel? = UILabel();
var currentCount = 0;
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 addOneBUtton(_ sender: UIButton) {
currentCount = currentCount + 1
if currentCount <= 1 {
outputLabel?.text = "\(currentCount) click"
} else {
outputLabel?.text = "\(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
#IBOutlet var oddSwitch: UISwitch!
#IBAction func oddToggle(_ sender: UISwitch) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
}
}
}
I'm confused as to the relationship between the #IBOutlet and my function that states to count in increments of three. I've tried including weak storage as well but it's to my understanding that is the default for #IBOutlet. Currently when I toggle the switch on, the counter still increments by 1.
My error log simply shows compression errors for PNGs for my splash screen, nothing with the code. What exactly is happening?
Change your addOneBUtton code to match this.
#IBAction func addOneBUtton(_ sender: UIButton) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
} else {
currentCount = currentCount + 1
}
if currentCount <= 1 {
outputLabel?.text = "\(currentCount) click"
} else {
outputLabel?.text = "\(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
And you can remove this section.
#IBAction func oddToggle(_ sender: UISwitch) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
}
}
So the complete code should look something like this.
import UIKit
class testViewController: UIViewController {
//MARK: IBOutlets
#IBOutlet var outputLabel: UILabel? = UILabel();
#IBOutlet var oddSwitch: UISwitch!
//MARK: Vars
var currentCount = 0;
//MARK: Lifecyle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: IBActions
#IBAction func addOneBUtton(_ sender: UIButton) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
} else {
currentCount = currentCount + 1
}
if currentCount <= 1 {
outputLabel?.text = "\(currentCount) click"
} else {
outputLabel?.text = "\(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
}
Note: This was my twist on keeping the code clean with IBOutlets all in one spots and using //MARK: to the sections of code quicker to jump to.
Related
I am learning swift3 programming but after executing my calculator app its crashing in between. Please check the below code.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var commmon_button: UIButton!
var a: Int?
var b: Int?
var sum: Int?
var val = ""
#IBOutlet weak var text_feild: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func clik_button(_ sender: UIButton) {
val=String(sender.tag)
text_feild.text = text_feild.text! + val
}
#IBAction func fn_addition(_ sender: UIButton) {
a = Int(text_feild.text!)
}
#IBAction func fn_answer(_ sender: UIButton) {
b = Int(text_feild.text!)
sum = a! + b!
a = 0
b = 0
text_feild.text = nil
text_feild.text = String(sum!)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
During run time i am getting crash at fn_addition by saying Thread 1 breakpoint 2.1
Initiliaze your variables as below
var a = 0
var b = 0
var sum = 0
Replace your methods with below methods.
#IBAction func clik_button(_ sender: UIButton) {
guard let value = String(sender.tag), let text = text_feild.text
else {
return
}
text_feild.text = text + value
}
#IBAction func fn_addition(_ sender: UIButton) {
guard let aValue = Int(text_feild.text)
else{
return
}
a = aValue
}
#IBAction func fn_answer(_ sender: UIButton) {
guard let bValue = Int(text_feild.text)
else{return}
b = bValue
sum = a + b
a = 0
b = 0
text_feild.text = ""
text_feild.text = String(sum)
}
Suggestion: You are using same text field for taking a , b values and for showing sum result. It is better to use two different text fields for taking a and b values separately. Take a label to show sum value.
Hey guys I need some one to help me finish my app, I need to finish it before Dec 15. I'm making a Tip Calculator Project in Swift2 and It must have a settings view where I select the default tip rate. I have some issues with passing data, when I select a default tip percentage it doesn't change in the View Controller, also I want to make the app remember the default rate when I close the app and reopened. I will really appreciate that some one corrects my code and test it. Im new in this, below is the code of the two ViewControllers and a screenshot of the Main.Storyboard (Image 1) (ViewController Screenshot)
My apologies for my bad English, is not my native language
ViewController
import UIKit
class ViewController: UIViewController {
//Inputs
#IBOutlet weak var amountTextField: UITextField!
//Labels
#IBOutlet weak var TipPercentageLabel: UILabel!
#IBOutlet weak var numberOfPersonLabel: UILabel!
#IBOutlet weak var tipAmountLabel: UILabel!
#IBOutlet weak var totalBillLabel: UILabel!
#IBOutlet weak var billPerPersonLabel: UILabel!
//Slider & Stepper
#IBOutlet weak var tipSlider: UISlider!
#IBOutlet weak var personsStepper: UIStepper!
//Variables
var tipPercentage = 0.20
var numberOfPerson:Int = 1
let numberFormatter:NSNumberFormatter = NSNumberFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipAmountLabel.text = "$0.00"
totalBillLabel.text = "Bill Total"
billPerPersonLabel.text = "$0.00"
TipPercentageLabel.text = "20.0%"
numberOfPersonLabel.text = "1"
self.amountTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupContainer() {
tipSlider.minimumValue = 0
tipSlider.maximumValue = 100
tipSlider.value = 20
tipSlider.addTarget(self, action: "sliderTipChanged:", forControlEvents: .ValueChanged)
personsStepper.minimumValue = 1
personsStepper.maximumValue = 30
personsStepper.value = 1
personsStepper.addTarget(self, action: "sliderPersonChanged:", forControlEvents: .ValueChanged)
amountTextField.text = ""
refreshCalculation()
}
#IBAction func OnEditingFieldBill(sender: AnyObject) {
refreshCalculation()
}
func refreshCalculation() {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let amount = numberFormatter.numberFromString(amountTextField.text!) as? Double {
let tipAmount = amount * tipPercentage
let totalBill = amount + tipAmount
let billPerPerson = totalBill / Double(numberOfPerson)
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
tipAmountLabel.text = numberFormatter.stringFromNumber(tipAmount)
totalBillLabel.text = numberFormatter.stringFromNumber(totalBill)
billPerPersonLabel.text = numberFormatter.stringFromNumber(billPerPerson)
} else {
tipAmountLabel.text = "-"
totalBillLabel.text = "-"
billPerPersonLabel.text = "-"
}
numberFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle
numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 1
TipPercentageLabel.text = self.numberFormatter.stringFromNumber(tipPercentage)
numberOfPersonLabel.text = "\(numberOfPerson)"
}
#IBAction func sliderTipChanged(sender: AnyObject) {
tipPercentage = Double(round(tipSlider.value)) / 100
refreshCalculation()
}
#IBAction func StepperPersonChanged(sender: AnyObject) {
numberOfPerson = Int(round(personsStepper.value))
refreshCalculation()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier {
if id == "show settings" {
if let SettingsViewController = segue.destinationViewController as? SettingsViewController {
}
}
}
}
}
Settings View Controller
import UIKit
class SettingsViewController: UIViewController {
#IBOutlet weak var tipControl: UISegmentedControl!
var tipRates:Double?
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.
}
#IBAction func DefaultRate(sender: AnyObject) {
var tipRate = [5, 10, 15, 20, 25, 30]
var tipRates = Double(tipRate[tipControl.selectedSegmentIndex])
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier {
if id == "goBackToViewController" {
if let ViewController = segue.destinationViewController as? ViewController {
if let tip = tipRates {
ViewController.tipPercentage = tip/100
}
}
}
}
---- Edit from comments ----
I think the reason it is not updating as you would like is due to a minor error with this line.
var tipRates = Double(tipRate[tipControl.selectedSegmentIndex])
Inside of your DefaultRate action function for the UISegmentedControl
Using var is a redeclaration of the same variable name, thus what you are trying to pass in the prepareForSegue is an empty variable.
This function should be changed to:
#IBAction func DefaultRate(sender: AnyObject) {
var tipRate = [5, 10, 15, 20, 25, 30]
tipRates = Double(tipRate[tipControl.selectedSegmentIndex])}
Hopefully this will now solve the error.
---- End Edit ----
From what I can see in the viewDidLoad function of your viewController, you are setting the tip label, and not updating the value based on the variable var tipPercentage.
TipPercentageLabel.text = "20.0%"
is setting the value display to always be 20.0%, you could use this here.
var tipDisplay = tipPercentage * 100
TipPercentageLabel.text = "\(tipDisplay)%"
This should update the displayed value in the label, however you never call on your other functions to recalculate the amount etc.
Thus you should also be calling on
func setupContainer()
or
func refreshCalculation()
within your ViewDidLoad().
In terms of remembering the default value when the app is closed you should look into using NSUserDefaults.
Some information regarding NSUserDefaults can be found here, which explains implementing small amounts of saved data and can be implemented in your case quite simply.
I am having difficulty in making simple tally counter application. I have put the codes but when i hit "run simulation", it always gives error message. can anyone help me find my mistake? thank you.
my codes are like below:
import UIKit
class ViewController: UIViewController {
var counter: Int!
#IBOutlet weak var Display: UILabel!
func updateDisplay() {
Display.text = String(counter)
}
override func viewDidLoad() {
super.viewDidLoad()
counter = 0
updateDisplay()
// 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 PlusButton(sender: AnyObject) {
counter = counter + 1
updateDisplay()
}
#IBAction func MinusButton(sender: AnyObject) {
counter = counter - 1
updateDisplay()
}
#IBAction func ClearButton(sender: AnyObject) {
counter = 0
updateDisplay()
}
}
here is the appearance in the Xcode
https://www.facebook.com/photo.php?fbid=10204747519271053&set=pcb.10204747520111074&type=1&theater
here is the error message when i hit run simulation
https://www.facebook.com/photo.php?fbid=10204747519351055&set=pcb.10204747520111074&type=1&theater
Your code is working fine but I think you have problem with layOut connection so check it again and it should be like this:
For Display label:
For PlusButton :
For MinusButton:
And For ClearButton:
Check THIS sample project for more Info.
I'm creating a simple app using Swift that tells you if the number you are entering is a prime number or not. I know the logic is correct, but when I run the app and enter a number and press the button my label is not updating like it should. Can someone help me?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var number: UITextField!
#IBOutlet weak var results: UILabel!
#IBAction func buttonPressed(sender: AnyObject) {
var numberInt = number.text.toInt()
if numberInt != nil {
var unwrappedNumber = numberInt!
var isPrime = true
if unwrappedNumber == 1 {
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1 {
for var i = 2; i < unwrappedNumber; i++ {
if unwrappedNumber % i == 0 {
isPrime = false
}
}
}
if isPrime == true{
results.text = "\(unwrappedNumber)Is Prime"
}else {
results.text = "\(unwrappedNumber)Is not Prime"
}
}else {
results.text = "Enter a number"
}
}
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.
}
}
The problem in your project is you are performing a wrong action at wrong place like in your StoryBoard you right Click on TextField you find that you connected Editing Did End is connected with #IBAction func buttonPressed(sender: AnyObject) this action. because of this your action is not working.
Now the solution for your problem is remove your action connection from that textField by Clicking that cross button and it will look like :
after that connect ** buttonPressed** action with Run Test Button like this:
HERE I updated your code.
I recommended you to watch some tutorial on UI so you can batter understands how this all things works.
I can't seem to write the if statement in the end to make the outs go up when the strikes hit 3?
can someone lease help and make it so in swift the outs will go up when someone hits 3 strikes
//
// ViewController.swift
// helloWordDemo
//
// Created by Developer on 6/8/14.
// Copyright (c) 2014 AECApps. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
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.
}
#IBOutlet var labelDispaly : UILabel = nil
// dispaly Strikes
var counter = 1
#IBAction func buttonPressed(sender : AnyObject) {
labelDispaly.text = "Strikes \(counter++)"
}
//button to add strikes
#IBOutlet var OutsDispaly : UILabel = nil
var outsCounter = 1
//outs dispaly
#IBAction func outsButtonPressed(sender : AnyObject) {
OutsDispaly.text = "Outs \(outsCounter++)"
}
//button to add outs
if counter = 3 {
outsCounter ++
}
}
Use a property observer:
var counter = 1 {
didSet {
if counter == 3 {
self.outsCounter++
}
}
}
Whenever counter gets changed, didSet will be called.
(Also note that the equality operator is ==. = is for assignment.)