I have a UIStepper that increments/decrements by 1 to a UILabel, I want to have a additional +3 button, when the +3 is pressed it does add 3 to the Label, but then if you press the UIStepper it goes back to 1.
My code is below:
import Foundation
import UIKit
import AVFoundation
class ViewTwo : UIViewController, AVAudioPlayerDelegate {
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
/// Actions de sonido -------
#IBAction func stepperSoundRed(sender: UIStepper) {
audioPlayer.play()
}
#IBAction func stepperSoundBlue(sender: UIStepper) {
audioPlayer.play()
}
/////////////////////////
// el nombre del equipo Blue
#IBOutlet weak var teamBlueTextLabel: UILabel!
var BlueName = String()
// nombre del equipo rojo
#IBOutlet weak var teamRedTextLabel: UILabel!
var RedName = String()
// score inicial del equipo rojo
#IBOutlet weak var RedScoreLabel: UILabel!
var RedScore = String()
// score initcial equipo azul
#IBOutlet weak var BlueScoreLabel: UILabel!
var BlueScore = String()
// que funcionen los Steppers
#IBOutlet weak var RedStepperUI: UIStepper!
#IBOutlet weak var BlueStepperUI: UIStepper!
// Botón Done
#IBOutlet weak var BotonDone: UIButton!
#IBAction func BlueStepperValueChange(sender: UIStepper) {
BlueScoreLabel.text = Int(sender.value).description
}
#IBAction func RedStepperValueChange(sender: UIStepper) {
RedScoreLabel.text = Int(sender.value).description
}
#IBOutlet weak var periodUILabel: UILabel!
// archivos de sonidos
var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping2", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
required init? (coder aDecoder: NSCoder){
super.init(coder: aDecoder)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
//audioPlayer.play()
} catch {
// Errors here
}
}
#IBAction func BackToViewOne(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Landscape
}
// Period
#IBOutlet weak var periodUILabel2: UILabel!
#IBAction func periodAdd1(sender: UIButton) {
if(periodUILabel.text == "20") {
}
else {
let period = Int(periodUILabel.text!)!+1
periodUILabel.text = String(period)
}
}
#IBAction func periodMinus1(sender: UIButton) {
if(periodUILabel.text == "0") {
}
else {
let period = Int(periodUILabel.text!)!-1
periodUILabel.text = String(period)
}
}
// VIEW DID LOAD
override func viewDidLoad() {
// No se para que es esto??
super.viewDidLoad()
BotonDone.layer.cornerRadius = 5
// Checamos si están vacios los nombres
if BlueName.isEmpty {
BlueName = "BLUE"
}
if RedName.isEmpty {
RedName = "RED"
}
if RedScore.isEmpty {
RedScore = "0"
}
if BlueScore.isEmpty {
BlueScore = "0"
}
// Proseguimos a asignarlos a las Labels
teamBlueTextLabel.text = BlueName
teamRedTextLabel.text = RedName
RedScoreLabel.text = RedScore
BlueScoreLabel.text = BlueScore
// Aqui vemos el Red +/-
RedStepperUI.wraps = true
RedStepperUI.autorepeat = false
RedStepperUI.value = Double(RedScore)!
RedStepperUI.maximumValue = 999
// aqui vemos el Blue +/-
BlueStepperUI.wraps = true
BlueStepperUI.autorepeat = false
BlueStepperUI.value = Double(BlueScore)!
BlueStepperUI.maximumValue = 999
//
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
// BOTONES MAS +3
#IBAction func RedPlus3UIButton(sender: UIButton) {
let CurrentScoreRed = RedStepperUI.value;
RedScoreLabel.text = String (Int(CurrentScoreRed) + 3)
audioPlayer.play()
}
#IBAction func BluePlus3UIButton(sender: UIButton) {
audioPlayer.play()
}
// BOTONES + Y -
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let DestViewController : ViewThree = segue.destinationViewController as! ViewThree
DestViewController.FinalScoreBlue = BlueScoreLabel.text!
DestViewController.FinalScoreRed = RedScoreLabel.text!
DestViewController.TeamNameR1Label = teamRedTextLabel.text!
DestViewController.TeamNameB1Label = teamBlueTextLabel.text!
}
}
class MyButtons : UIButton {
required init(coder aDecoder: (NSCoder!)) {
super.init(coder: aDecoder)!
self.layer.cornerRadius = 5
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 1
}
}
This is the +3 button:
#IBAction func RedPlus3UIButton(sender: UIButton) {
let CurrentScoreRed = RedStepperUI.value;
RedScoreLabel.text = String (Int(CurrentScoreRed) + 3)
audioPlayer.play()
}
You need to update the stepper's value property. Example:
#IBAction func RedPlus3UIButton(sender: UIButton) {
RedStepperUI.value += 3
let CurrentScoreRed = RedStepperUI.value
RedScoreLabel.text = String(Int(CurrentScoreRed))
audioPlayer.play()
}
Related
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.
I am making an application that keeps score from 1 to 20 and then displays an image if the score is >= 21. However I don't know how to go about this, I have a label that displays the users score in integers. Is there a way that I can add an image to the array after 20? Or is there a way to add a string when score >= 21 that says "Bullseye" either the string or image. I just dont know the best way to do this any help?
import UIKit
class ViewController: UIViewController {
//Below are all of the labels at the top of AZG
#IBOutlet weak var user1name: UILabel!
#IBOutlet weak var user2name: UILabel!
#IBOutlet weak var lbl_currentPlayer: UILabel!
#IBOutlet weak var user1score: UILabel!
#IBOutlet weak var user2score: UILabel!
//Below are all the declared variables
var usernames = ["Big Meat ", "J Hooks "]
var currentPlayer = 0
var scores = [0,0]
var count = 0
var sdCount = 0
override func viewDidLoad() {
super.viewDidLoad()
setupGame()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func newGame() {
user1score.text = "\(count)"
user2score.text = "\(count)"
user1name.text = "\(usernames[0])"
user2name.text = "\(usernames[1])"
lbl_currentPlayer.text = usernames[currentPlayer]
scores = [0,0]
}
func setupGame() {
user1score.text = "\(count)"
user2score.text = "\(count)"
user1name.text = "\(usernames[0])"
user2name.text = "\(usernames[1])"
lbl_currentPlayer.text = usernames[currentPlayer]
}
func updateTurn() {
lbl_currentPlayer.text = usernames[currentPlayer]
user1score.text = "\(scores[0])"
user2score.text = "\(scores[1])"
}
func attackTurnUpdate() {
currentPlayer = 1 - currentPlayer
}
func resetAttackTurn() {
currentPlayer = 1 - currentPlayer
}
func missedNextTurn() {
currentPlayer = 1 - currentPlayer
}
func suddenDeath() {
sdCount = sdCount++
}
func takeStepBack() {
}
func bullseyeDisplay() {
}
#IBAction func hitSingle(sender: AnyObject) {
scores[currentPlayer]++
updateTurn()
}
#IBAction func nextTurn(sender: AnyObject) {
currentPlayer = 1 - currentPlayer
updateTurn()
}
Just add the image to your view in interface builder (with an appropriate IBOutlet in your code) and set "Hidden" on it.
Then when you want to display the image, just change the value of hidden:
my image.hidden = false
Hey guys I need some help here with my code, please take a look to the images to see what I see. I'm making a Tip Calculator Project in Swift and I must have a settings view where I select the default tip rate. I have some errors and I must fix that as soon as posible. I will really appreciate that some one corrects my code and test it. Below is the code of the two ViewControllers, I did not post the image of the Settings View Controller because the website does not let me post more than two links until I get more reputation.
The error in Xcode:
Storyboard: Check the images I have some errors at the first lines.
import UIKit
class ViewController: UIViewController, SettingDelegate {
// 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 : Double = NSUserDefaults.standardUserDefaults().doubleForKey("DefaultTipRate") ?? 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: UISlider) {
tipPercentage = Double(round(tipSlider.value)) / 100
refreshCalculation()
}
#IBAction func StepperPersonChanged(sender: UIStepper) {
numberOfPerson = Int(round(personsStepper.value))
refreshCalculation()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let SettingsViewController = segue.destinationViewController as?SettingsViewController {
SettingsViewController.delegate = self
refreshCalculation()
}
}
}
The SettingsViewController below:
import UIKit
protocol SettingDelegate {
func tipPercentageChanged(newValue : Double)
}
class SettingsViewController: UIViewController {
var destName : String!
var delegate : SettingDelegate?
#IBOutlet weak var tipControl: UISegmentedControl!
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 tipRates = [0.05, 0.10, 0.15, 0.20, 0.25, 0.30]
let tipRate = tipRates[tipControl.selectedSegmentIndex]
delegate?.tipPercentageChanged(tipRate)
NSUserDefaults.standardUserDefaults().setDouble(tipRate, forKey: "DefaultTipRate")
NSUserDefaults.standardUserDefaults().synchronize()
}
/
For your first error:
When a viewController conforms to a protocol, it needs to implements the methods the protocol implements. In your case, define you should have
func tipPercentageChanged(newValue : Double) {
//save the new value here
}
The first error should go away.
It looks like you are presenting the SettingsViewController using a modal transition, so you can use
self.dismissViewControllerAnimated(true, completion: {})
I have a problem with a little App I am programming & learning with. I finally added a sound that it's supposed to play when you press a Stepper, and it does, the problem is that it's also playing when you press a different button.
I honestly have no idea why it happens and how to fix it.
Any help?
here's my code:
ViewONE (here the button that shouldn't be playing the audio file is "BotonLetsBegin"
//
// ViewONE.swift
// Simple Score
//
// Created by Juan Francisco Mellado on 10/1/15.
// Copyright © 2015 Juan Francisco Mellado. All rights reserved.
//
import Foundation
import UIKit
class ViewONE: UIViewController, UITextFieldDelegate {
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
#IBOutlet weak var ScrollViewOne: UIScrollView!
#IBOutlet weak var teamRedName: UITextField!
#IBOutlet weak var initScoreRed: UITextField!
#IBAction func BotonLetsBeginAction(sender: UIButton) {
}
#IBOutlet weak var BotonLetsBegin: UIButton!
#IBOutlet weak var teamBlueName: UITextField!
#IBOutlet weak var initScoreBlue: UITextField!
#IBAction func userTappedBackground(sender: AnyObject) {
view.endEditing(true)
}
#IBAction func userTappedThisView(sender: AnyObject) {
view.endEditing(true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let DestViewController : ViewTwo = segue.destinationViewController as! ViewTwo
// Cambiamos los valores si no existen a 0
if(initScoreRed.text == ""){
initScoreRed.text = "0"
}
if(initScoreBlue.text == ""){
initScoreBlue.text = "0"
}
//---------
DestViewController.RedName = teamRedName.text!
DestViewController.BlueName = teamBlueName.text!
DestViewController.RedScore = initScoreRed.text!
DestViewController.BlueScore = initScoreBlue.text!
}
override func viewDidLoad() {
super.viewDidLoad()
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
BotonLetsBegin.layer.cornerRadius = 5
self.initScoreBlue.delegate = self
self.initScoreRed.delegate = self
}
let TEXT_FIELD_LIMIT = 3
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
switch textField {
case initScoreBlue:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
case initScoreRed:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
case teamBlueName:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= 25
case teamRedName:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= 25
default:
return true
}
}
//For Swift 1.2
//return count((textField.text ?? "").utf16) + count(string.utf16) - range.length <= TEXT_FIELD_LIMIT
override func shouldAutorotate() -> Bool {
return false
}
func textFieldDidBeginEditing(textField: UITextField) {
if (textField == initScoreBlue){
ScrollViewOne.setContentOffset(CGPointMake(0, 250), animated: true)
}
if (textField == teamBlueName){
ScrollViewOne.setContentOffset(CGPointMake(0, 250), animated: true)
}
if (textField == teamRedName){
ScrollViewOne.setContentOffset(CGPointMake(0, 100), animated: true)
}
if (textField == initScoreRed){
ScrollViewOne.setContentOffset(CGPointMake(0, 100), animated: true)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
ScrollViewOne.setContentOffset(CGPointMake(0, 0), animated: true)
}
// - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//[textField resignFirstResponder];
//}
}
Here is ViewTwo where the steppers are
//
// ViewTWO.swift
// Simple Score
//
// Created by Juan Francisco Mellado on 9/29/15.
// Copyright © 2015 Juan Francisco Mellado. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
class ViewTwo : UIViewController, AVAudioPlayerDelegate {
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
/// Actions de sonido -------
#IBAction func stepperSoundRed(sender: UIStepper) {
audioPlayer.play()
}
#IBAction func stepperSoundBlue(sender: UIStepper) {
audioPlayer.play()
}
/////////////////////////
// el nombre del equipo Blue
#IBOutlet weak var teamBlueTextLabel: UILabel!
var BlueName = String()
// nombre del equipo rojo
#IBOutlet weak var teamRedTextLabel: UILabel!
var RedName = String()
// score inicial del equipo rojo
#IBOutlet weak var RedScoreLabel: UILabel!
var RedScore = String()
// score initcial equipo azul
#IBOutlet weak var BlueScoreLabel: UILabel!
var BlueScore = String()
// que funcionen los Steppers
#IBOutlet weak var RedStepperUI: UIStepper!
#IBOutlet weak var BlueStepperUI: UIStepper!
// Botón Done
#IBOutlet weak var BotonDone: UIButton!
#IBAction func BlueStepperValueChange(sender: UIStepper) {
BlueScoreLabel.text = Int(sender.value).description
}
#IBAction func RedStepperValueChange(sender: UIStepper) {
RedScoreLabel.text = Int(sender.value).description
}
// archivos de sonidos
var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping2", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
required init? (coder aDecoder: NSCoder){
super.init(coder: aDecoder)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play()
} catch {
// Errors here
}
}
// VIEW DID LOAD
override func viewDidLoad() {
// No se para que es esto??
super.viewDidLoad()
BotonDone.layer.cornerRadius = 5
// Checamos si están vacios los nombres
if BlueName.isEmpty {
BlueName = "TEAM BLUE"
}
if RedName.isEmpty {
RedName = "TEAM RED"
}
// Proseguimos a asignarlos a las Labels
teamBlueTextLabel.text = BlueName
teamRedTextLabel.text = RedName
RedScoreLabel.text = RedScore
BlueScoreLabel.text = BlueScore
// Aqui vemos el Red +/-
RedStepperUI.wraps = true
RedStepperUI.autorepeat = false
RedStepperUI.value = Double(RedScore)!
RedStepperUI.maximumValue = 999
// aqui vemos el Blue +/-
BlueStepperUI.wraps = true
BlueStepperUI.autorepeat = false
BlueStepperUI.value = Double(BlueScore)!
BlueStepperUI.maximumValue = 999
//
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
override func shouldAutorotate() -> Bool {
return false
}
}
Your issue is in init(...) method of ViewTwo. You create a player and call the play() method :
required init? (coder aDecoder: NSCoder){
super.init(coder: aDecoder)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play() // this is your problem ;)
} catch {
// Errors here
}
}
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