Segmented Control in Calculator - ios

Im trying to make a Segmented Control that holds two values, but I'm having trouble making it. I want to multiply the input by whatever side is picked in the segmented view and displayed in the label, but I keep running into errors. Any help?
#IBOutlet var input: UITextField!
#IBOutlet var output: UILabel!
#IBOutlet var controller: UISegmentedControl!
#IBAction func convert(sender: UIButton) {
}
#IBAction func change(sender: AnyObject) {
if controller.selectedSegmentIndex == 0 {
result = number1 * 1
}
if controller.selectedSegmentIndex == 1 {
result = number1 * 5
}
let number1 = Double(input.text!)
label.text = "\(result)"
}

Why you use "number1" before declaration?
Try this:
#IBOutlet var input: UITextField!
#IBOutlet var output: UILabel!
var result:Double! //fixed "cannot be applied to Double and Int." problem
#IBOutlet var controller: UISegmentedControl!
#IBAction func convert(sender: UIButton) {
}
#IBAction func change(sender: AnyObject) {
let number1 = Double(input.text!)
if controller.selectedSegmentIndex == 0 {
self.result = number1 * 1
}
if controller.selectedSegmentIndex == 1 {
self.result = number1 * 5
}
label.text = "\(result)"
}

Related

Swift NSTiimer not following specified Interval

I am trying to create a quiz app which has a timer for each question when the timer expires (i.e. 10 seconds and I want Timer to have an interval of 1 sec) it resets it self and next question is fetched and Timer again restart from 10... But my issue is the timer doesn't follow a fixed interval when first question is loaded it shows interval of 2 ... i.e. 10,8,6 .. and then for second question it makes jump for 3 secs interval and similarly the interval increases.
import UIKit
class ViewController: UIViewController {
let allQuestions = QuestionsBundle()
var pickedAnswer : Int = 0
var questionCounter = 0
var score : Int = 0
var timer: Timer!
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var countDownLabel: UILabel!
#IBOutlet weak var ansLbl1: UILabel!
#IBOutlet weak var ansLbl2: UILabel!
#IBOutlet weak var ansLbl3: UILabel!
#IBOutlet weak var ansLbl4: UILabel!
#IBOutlet weak var checkBox1: CheckBox!
#IBOutlet weak var checkBox2: CheckBox!
#IBOutlet weak var checkBox3: CheckBox!
#IBOutlet weak var checkBox4: CheckBox!
var checkBoxlist : [CheckBox] = []
#IBAction func correct_Answer_Checbox_Btn(_ sender: AnyObject) {
//print("\(sender.tag) <==> \(String(describing: question?.correctAnswer))")
updateCheckBoxes(sender: sender)
if sender.tag == question?.correctAnswer{
question?.isAnswerCorrect = true
question?.selectedAnswer = sender.tag
//score = score + 1
}
else {
question?.isAnswerCorrect = false
}
}
func updateCheckBoxes(sender: AnyObject){
for checkBoxItem in checkBoxlist{
if checkBoxItem.tag != sender.tag {
checkBoxItem.isChecked = false
}
}
}
#IBOutlet weak var nextButton: UIButton!
#IBAction func nextBtnClicked(_ sender: AnyObject) {
do{
try handleNextQuestion()
}
catch{
moveToResultView()
}
}
func handleNextQuestion() throws {
nextQuestion()
if questionCounter == allQuestions.list.count-1{
finishButton.isHidden = false
nextButton.isHidden = true
//scoreLbl.text = "\(score)"
}
}
var question : Question?
var countTime = 10.0
override func viewDidLoad() {
super.viewDidLoad()
finishButton?.isHidden = true
checkBoxlist = fetchCheckBoxList()
question = fetchQuestion()
setQuizView(question: question!)
// Do any additional setup after loading the view, typically from a nib.
}
// set all questions in a function
#objc func update() {
if(countTime > 0) {
countTime = countTime - 1
self.countDownLabel.text = String(countTime)
}else{
timer.invalidate()
countTime = 10.0
do{
try handleNextQuestion()
}
catch{
moveToResultView()
}
}
}
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
}
func setQuizView(question:Question) {
self.countDownLabel.text = "10"
startTimer()
questionLabel.text = question.questionText
ansLbl1.text = question.answer1
ansLbl2.text = question.answer2
ansLbl3.text = question.answer3
ansLbl4.text = question.answer4
if question.selectedAnswer == Constants.DEFAULT_ANSWER {
for checkBoxItem in checkBoxlist{
checkBoxItem.isChecked = false
}
}
}
#IBOutlet weak var finishButton: UIButton!
// prepare segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == resultScreenIdentifier{
let vc = segue.destination as! ResultViewController
vc.data = sender as! String
}
}
let resultScreenIdentifier = "resultScreenSegue"
func moveToResultView(){
performSegue(withIdentifier: resultScreenIdentifier, sender: score)
}
#IBAction func finishButtonClicked(_ sender: UIButton) {
//perform segue
let score = "\(calculateScore())"
moveToResultView()
}
// calculate the score of quiz using loop
func calculateScore()->Int{
var numOfCorrectAnswers = 0
for question in allQuestions.list{
if question.isAnswerCorrect {
numOfCorrectAnswers = numOfCorrectAnswers + 1
//print(numOfCorrectAnswers)
}
}
return numOfCorrectAnswers
}
func nextQuestion(){
showResultView(isCorrect: (question?.isAnswerCorrect)!)
questionCounter = questionCounter + 1
question = fetchQuestion()
setQuizView(question: question!)
}
func fetchQuestion() -> Question{
return allQuestions.list[questionCounter]
}
func fetchCheckBoxList() -> [CheckBox]{
let arr : [CheckBox] = [checkBox1,checkBox2,checkBox3,checkBox4]
return arr
}
}
Timers are not particularly accurate. They can suffer from significant jitter.
A better approach is to create a Date that represents the expiration time (ie Date(timeIntervalSinceNow:10) and then run a Timer with a much shorter interval (I would suggest around 0.1 second). You can then calculate the time remaining based on the target Date and check if the target date is in the past.

Calculating and displaying as label

I want to calculate Runs per Overs and display on a Run Rate Label.
As you can see in my code, the Run Rate will change as i'm using steppers for Runs and Overs.
The run rate need to be displayed up to 2 decimal points (eg. 4.50 or 10.74 etc.)
I want to create function but I don't know how to calculate.
How can I do this?
// RUNS
var runsInt = 0
var oversFloat: Float = 0.0
var runRate: Double = 0.0
#IBOutlet weak var runsLabel: UILabel!
#IBOutlet weak var displayRunsLabel: UILabel!
#IBOutlet weak var oversLabel: UILabel!
#IBOutlet weak var oversRectangle: UILabel!
#IBOutlet weak var displayOversLabel: UILabel!
#IBOutlet weak var runRateLabel: UILabel!
#IBOutlet weak var displayRunRateLabel: UILabel!
#IBAction func RunStepper(_ sender: UIStepper) {
let runsValue = Int(sender.value)
displayRunsLabel.text = String(runsValue)
}
// OVERS
#IBAction func OversStepper(_ sender: UIStepper) {
let value = Int(sender.value)
let remainder = value % 10
if remainder == 6 {
sender.value = Double(value + 4)
} else if remainder == 9 {
sender.value = Double(value - 4)
}
displayOversLabel.text = String(format: "%.1f", sender.value / 10)
}
I used this page for information on calculating run rate.
runRate = (total runs scored)/(total overs faced)
Note: If overs is 47.5, the stepper value will be 475.0 and
oversInt will be set to 475. When calculating runRate, 47.5
actually represents 47 5/6 which we can calculate as
Double(oversInt / 10) + Double(oversInt % 10) / 6
Create a function called calculateRunRate and
add property observers (didSet) to runsInt and oversInt to trigger the calculation of runRate. Then anytime either of those values changes, runRate will be recalculated and the displayRunRate label will be updated.
// RUNS
var runsInt = 0 {
didSet {
calculateRunRate()
}
}
#IBOutlet weak var runsLabel: UILabel!
#IBOutlet weak var displayRunsLabel: UILabel!
#IBAction func RunStepper(_ sender: UIStepper) {
runsInt = Int(sender.value)
displayRunsLabel.text = String(runsInt)
}
// OVERS
var oversInt = 0 {
didSet {
calculateRunRate()
}
}
#IBOutlet weak var oversLabel: UILabel!
#IBOutlet weak var oversRectangle: UILabel!
#IBOutlet weak var displayOversLabel: UILabel!
#IBAction func OversStepper(_ sender: UIStepper) {
var value = Int(sender.value)
let remainder = value % 10
if remainder == 6 {
value += 4
} else if remainder == 9 {
value -= 4
}
sender.value = Double(value)
oversInt = value
displayOversLabel.text = String(format: "%.1f", sender.value / 10)
}
// RUN RATE
var runRate = 0.0
let maxOvers = 40.0
#IBOutlet weak var runRateLabel: UILabel!
#IBOutlet weak var displayRunRateLabel: UILabel!
#IBOutlet weak var displayRequiredRunRateLabel: UILabel!
func calculateRunRate() {
var oversDouble = 0.0
// Don't divide by zero
if oversInt == 0 {
// can this even happen?
// set runRate to some value that makes sense
runRate = 0.0
} else {
oversDouble = Double(oversInt / 10) + Double(oversInt % 10) / 6
runRate = Double(runsInt) / oversDouble
}
displayRunRateLabel.text = String(format: "%.2f", runRate)
// required run rate
let targetScore = Int(targetScoreLabel.text ?? "") ?? 0
var requiredRunRate = 0.0
if oversDouble < maxOvers {
requiredRunRate = Double(targetScore - runsInt) / (maxOvers - oversDouble)
}
displayRequiredRunRateLabel.text = String(format: "%.2f", requiredRunRate)
}

How can I perform addition automatically in iOS?

I work on a e-commerce project and now designing basket page. I create 4 steppers for determine to quantity of products. I create labels for show cost of each products and one label for total cost.
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
#IBAction func GmS1(_ sender: GMStepper) {
label1.text = String(sender.value*1.5)
}
#IBAction func GmS2(_ sender: GMStepper) {
label2.text = String(sender.value*0.89)
}
#IBAction func GmS3(_ sender: GMStepper) {
label3.text = String(sender.value*26)
}
#IBAction func GmS4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
}
I don't want to use button but I struggling in addition total cost automatically. My codes are above. Are there anybody know : How can ı addition 4 label in 1 label automatically(without any button).
Label5 for total cost.
You can check photo for general idea.
Make a function sumValues, add all the label's value in it, and assign string of sum to label5.text. This function can be then called from all the IBAction
#IBAction func GmS4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
sumValues()
}
In the function sumValues(),
set label5.text = string of sum of all the labels'.
SideNote - Make sure to initialize value of all labels to 0 in viewDidLoad().
You can try to call this method from every action
func sumAll() {
let sum = [label1,label2,label3,label4].map { Int($0.text ?? "0" ) ?? 0 }.reduce(0,+)
label5.text = "\(sum)"
}
Note: if word variable is part of the label text you may extract number from the text or declare the steppers as outlets and ask them about their current value and at this way use
let sum = [stepper1,stepper2,stepper3,stepper4].map{$0.value}.reduce(0,+)
Continuing from your previous question:
#IBAction func gmstp1(_ sender: GMStepper) {
label1.text = String(sender.value * 1.5)
calculateSum()
}
#IBAction func gmstp2(_ sender: GMStepper) {
label2.text = String(sender.value * 0.89)
calculateSum()
}
#IBAction func gmstp3(_ sender: GMStepper) {
label3.text = String(sender.value * 26.0)
calculateSum()
}
#IBAction func gmstp4(_ sender: GMStepper) {
label4.text = String(sender.value * 4.0)
calculateSum()
}
Where calculateSum is a function defined like so:
func calculateSum() {
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
label6.text = String(sum)
}
}
Or if you'd prefer a one-liner:
func calculateSum() {
label5.text = String([label1, label2, label3, label4].reduce(0,{$0 + (Double($1.text ?? "0") ?? 0)}))
}

Swift - Creating UIButton when in landscape

I am making a calculator app in iOS 9, Swift and with Xcode 7 and I would like to know how to create UIButtons when the user switches to landscape mode only. Adding more operators to the left of the number and AC Button and changing the constraints, shifting the buttons over to make room for the new ones. The basic calculator for iOS does this and I'm wondering how??
I'm new to iOS development and I have been web browsing to only find an overriding function called: viewWillTransitionToSize(). Is this the right function to do this sort of thing?
Also, everytime I enter the landscape view, another button gets created. How can I stop this from happening?
Attached is my programmatic creation of the UIbutton and the function I listed above.
Sorry for the array of questions/problems. I am having difficulties finding tutorials or help on this issue. Any guidance or solution will be helpful. Thank you so much.
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var outputDisplay: UILabel!
#IBOutlet weak var number7: UIButton!
#IBOutlet weak var number1: UIButton!
#IBOutlet weak var number2: UIButton!
#IBOutlet weak var number3: UIButton!
#IBOutlet weak var number4: UIButton!
#IBOutlet weak var number5: UIButton!
#IBOutlet weak var number6: UIButton!
#IBOutlet weak var number9: UIButton!
#IBOutlet weak var number8: UIButton!
#IBOutlet weak var numberZero: UIButton!
#IBOutlet weak var decimalPoint: UIButton!
#IBOutlet weak var plusMinusToggle: UIButton!
#IBOutlet weak var acClear: UIButton!
#IBOutlet weak var equalButton: UIButton!
#IBOutlet weak var multiply: UIButton!
#IBOutlet weak var divide: UIButton!
#IBOutlet weak var subtraction: UIButton!
#IBOutlet weak var addition: UIButton!
#IBOutlet weak var deletion: UIButton!
#IBOutlet weak var squareRoot: UIButton!
var typing:Bool = false
var firstNumber: Float = 0.0
var secondNumber: Float = 0.0
var operation:String = ""
var result: Float = 0.0
var valueToPass: Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
number1.layer.cornerRadius = number1.bounds.size.width / 8.0
number2.layer.cornerRadius = number2.bounds.size.width / 8.0
number3.layer.cornerRadius = number3.bounds.size.width / 8.0
number4.layer.cornerRadius = number4.bounds.size.width / 8.0
number5.layer.cornerRadius = number5.bounds.size.width / 8.0
number6.layer.cornerRadius = number6.bounds.size.width / 8.0
number7.layer.cornerRadius = number7.bounds.size.width / 8.0
number8.layer.cornerRadius = number8.bounds.size.width / 8.0
number9.layer.cornerRadius = number9.bounds.size.width / 8.0
numberZero.layer.cornerRadius = numberZero.bounds.size.width / 8.0
equalButton.layer.cornerRadius = equalButton.bounds.size.width / 8.0
deletion.layer.cornerRadius = deletion.bounds.size.width / 8.0
plusMinusToggle.layer.cornerRadius = plusMinusToggle.bounds.size.width / 8.0
decimalPoint.layer.cornerRadius = decimalPoint.bounds.size.width / 8.0
acClear.layer.cornerRadius = acClear.bounds.size.width / 8.0
addition.layer.cornerRadius = addition.bounds.size.width / 8.0
divide.layer.cornerRadius = divide.bounds.size.width / 8.0
multiply.layer.cornerRadius = multiply.bounds.size.width / 8.0
subtraction.layer.cornerRadius = subtraction.bounds.size.width / 8.0
squareRoot.layer.cornerRadius = squareRoot.bounds.size.width / 8.0
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
if (UIDevice.currentDevice().orientation.isLandscape) {
print("Device in Lanscape")
let newButton1 = UIButton(type: UIButtonType.System) as UIButton
newButton1.frame = CGRectMake(100, 100, 100, 50)
newButton1.backgroundColor = UIColor.whiteColor()
newButton1.center = CGPoint(x: number1.frame.width, y: number1.frame.height)
newButton1.layer.cornerRadius = newButton1.bounds.size.width / 8.0
self.view.addSubview(newButton1)
}
else{}
}
#IBAction func numberPressed(sender: AnyObject) {
// set the variable "number" to whichever number the user presses
let number = sender.currentTitle!
if typing {
outputDisplay.text = outputDisplay.text! + String(number!)
} else {
outputDisplay.text = number!
}
typing = true
}
#IBAction func calculationPressed(sender: AnyObject) {
typing = false
firstNumber = Float(outputDisplay.text!)!
operation = sender.currentTitle!!
}
#IBAction func equalPressed(sender: AnyObject) {
secondNumber = Float(outputDisplay.text!)!
typing = false
//arithmetic operations
if operation == "+" {
result = firstNumber + secondNumber
}
else if operation == "-" {
result = firstNumber - secondNumber
}
else if operation == "✕" {
result = firstNumber * secondNumber
}
else if operation == "÷" {
result = firstNumber / secondNumber
}
// else if operation == "%" {
// result = (firstNumber * secondNumber) / 100
// }
else if operation == "√" {
result = sqrt(firstNumber)
}
outputDisplay.text = "\(result)"
}
#IBAction func squareRoot(sender: AnyObject) {
result = sqrt(Float(outputDisplay.text!)!)
outputDisplay.text = "\(result)"
}
#IBAction func deletePressed(sender: AnyObject) {
if outputDisplay.text!.characters.count != 0 {
outputDisplay.text = outputDisplay.text!.substringToIndex(outputDisplay.text!.endIndex.predecessor())
}
else{
outputDisplay.text = "0"
}
}
#IBAction func plusMinus(sender: AnyObject) {
if( outputDisplay.text![outputDisplay.text!.startIndex] == "-"){
outputDisplay.text!.removeAtIndex(outputDisplay.text!.startIndex)
}else{
outputDisplay.text!.insert("-", atIndex: outputDisplay.text!.startIndex)
}
}
#IBAction func decimal(sender: AnyObject) {
let decimal = sender.currentTitle!
outputDisplay.text = outputDisplay.text! + decimal!
}
#IBAction func clear(sender: AnyObject) {
result = 0
firstNumber = 0
secondNumber = 0
outputDisplay.text = "0"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I would do this using Size Classes. You can design different layouts and button arrangements in storyboard using the different size classes. If this application is on the iPhone, you would use Compact width and Regular height when in Portrait and Compact height and Regular width when in Landscape.

Updating app to swift, trying to display a percentage

I am updating my app for swift. I am trying to display a percentage once the "calculate" button is pushed.
So far I have:
#IBAction func calculateButton(sender: UIButton) {
var calculated = (correctNumber / correctNumber + incorrectNumber * 100 )
calculateLabel.text = "\(calculated)"
}
Which I know is incorrect. How do I convert this to a percentage?
Full code below:
import UIKit
class ViewController: UIViewController {
var correctNumber = 0
var incorrectNumber = 0
var verbalNumber = 0
var visualNumber = 0
var tactileNumber = 0
//rightnumber____________________________________
#IBOutlet weak var correctLabel: UILabel!
#IBAction func correctUpButton(sender: UIButton) {
correctNumber += 1
correctLabel.text = "\(correctNumber)"
}
#IBAction func correctDownButton(sender: UISwipeGestureRecognizer) {
correctNumber -= 1
correctLabel.text = "\(correctNumber)"
}
//------------------------------------------------
//incorrectNumber________________________________
#IBOutlet weak var incorrectLabel: UILabel!
#IBAction func incorrectUpButton(sender: UIButton) {
incorrectNumber += 1
incorrectLabel.text = "\(incorrectNumber)"
}
#IBAction func incorrectDownButton(sender: UISwipeGestureRecognizer) {
incorrectNumber -= 1
incorrectLabel.text = "\(incorrectNumber)"
}
//end-------------------------------------------------
//verbalNumber________________________________
#IBOutlet weak var verbalLabel: UILabel!
#IBAction func verbalUpButton(sender: UIButton) {
verbalNumber += 1
verbalLabel.text = "\(verbalNumber)"
}
#IBAction func verbalDownButton(sender: UISwipeGestureRecognizer) {
verbalNumber -= 1
verbalLabel.text = "\(verbalNumber)"
}
//end-------------------------------------------------
//visualNumber________________________________
#IBOutlet weak var visualLabel: UILabel!
#IBAction func visualUpButton(sender: UIButton) {
visualNumber += 1
visualLabel.text = "\(visualNumber)"
}
#IBAction func visualDownButton(sender: UISwipeGestureRecognizer) {
visualNumber -= 1
visualLabel.text = "\(visualNumber)"
}
//end-------------------------------------------------
//tactileNumber________________________________________
#IBOutlet weak var tactileLabel: UILabel!
#IBAction func tactileUpButton(sender: UIButton) {
tactileNumber += 1
tactileLabel.text = "\(tactileNumber)"
}
#IBAction func tactileDownButton(sender: UISwipeGestureRecognizer) {
tactileNumber -= 1
tactileLabel.text = "\(tactileNumber)"
}
//end--------------------------------------------------
//calculate______________________________________________
#IBOutlet weak var calculateLabel: UILabel!
#IBAction func calculateButton(sender: UIButton) {
var calculated = (correctNumber / correctNumber + incorrectNumber * 100 )
calculateLabel.text = "\(calculated)"
}
//end----------------------------------------------------
//reset
#IBAction func resetButton(sender: UIButton) {
correctNumber = 0
correctLabel.text = ""
incorrectNumber = 0
incorrectLabel.text = ""
verbalNumber = 0
verbalLabel.text = ""
visualNumber = 0
visualLabel.text = ""
tactileNumber = 0
tactileLabel.text = ""
calculateLabel.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If i understand it correctly you need change line like this one:
var calculated = correctNumber / (correctNumber + incorrectNumber) * 100

Resources