Swift 2 + Xcode 7: Sound playing when wrong button is pressed - ios

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

Related

How can I stop the videobackground? [duplicate]

This question already has answers here:
How do i keep UISwitch state when changing ViewControllers?
(3 answers)
Closed 4 years ago.
How can I stop the videobackground when I move to another viewcontroller?
because when I move to another viewcontroller, the video and background music continue to be played, and when I go back to the main page two videos overlap. so I would like the video and the music to stop when I move to another viewcontroller, such as when I move in the viewcontroller for the sign up
import UIKit
import SwiftVideoBackground
import Firebase
import FirebaseAuth
class ViewController: UIViewController {
private let videoBackground = VideoBackground()
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var mute_img: UIImageView!
#IBOutlet private var muteSwitch: UISwitch!
#IBAction func `switch`(_ sender: UISwitch) {
if (sender.isOn == true)
{
mute_img.isHidden = false
videoBackground.isMuted = true
}
else
{
mute_img.isHidden = true
videoBackground.isMuted = false
}
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType:
"mp4", isMuted: shouldMute, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == usernameField {
passwordField.becomeFirstResponder()
} else if textField == passwordField {
textField.resignFirstResponder()
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Follow the steps:
1) Make an IBOutlet for the switch
#IBOutlet private var muteSwitch: UISwitch!
Don't forget to connect it to the switch in the storyboard.
2) Read the saved value from UserDefaults ( in viewDidLoad ):
override
func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType: "mp4", isMuted: shouldMute, alpha : 0.25, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
3) Save the switch value to UserDefaults ( in #IBAction func `switch`...) :
#IBAction func `switch`(_ sender: UISwitch) {
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}
1. Objective - C Version
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UISwitch *bluetoothSwitch;
- (IBAction)saveSwitchState:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"SwitchState"])
self.bluetoothSwitch.on = [defaults boolForKey:#"SwitchState"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveSwitchState:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([self.bluetoothSwitch isOn])
[defaults setBool:YES forKey:#"SwitchState"];
else
[defaults setBool:NO forKey:#"SwitchState"];
}
#end
Swift Version
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var stateSwitch: UISwitch!
#IBAction func buttonClicked(_ sender: Any) {
if stateSwitch.isOn {
textField.text = "The Switch is Off"
stateSwitch.setOn(false, animated:true)
} else {
textField.text = "The Switch is On"
stateSwitch.setOn(true, animated:true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
stateSwitch.addTarget(self, action: #selector(stateChanged), for: UIControlEvents.valueChanged)
}
#objc func stateChanged(switchState: UISwitch) {
if switchState.isOn {
textField.text = "The Switch is On"
} else {
textField.text = "The Switch is Off"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
if userDefaults.value(forKey: "isMuted") != nil{
let object = userDefaults.value(forKey: "isMuted") as? NSNumber
yourSwitch.isOn = (object?.boolValue)!
}
}
#IBAction func switchChanged(sender: UISwitch) {
let uDefault = UserDefaults.standard
if sender.isOn {
uDefault.setValue(NSNumber(value: true), forKey:"isMuted")
}
else {
uDefault.setValue(NSNumber(value: false), forKey:"isMuted")
}
}

segmentedcontrol / textfield / DidChange

I have a segmentedControl that give a string to a textfield. also i have 2 another textfields. one is for user input and the second for make a calculation from segmentedcontrol textfield and user input textfield. How can i automatically update the calculation textfield when segmentedcontrolindex will change.
For user input textfield the textfielddidchangemethod works. Thanks
#IBOutlet weak var segmentedcontrol: UISegmentedControl!
#IBOutlet weak var textf: UITextField!
#IBOutlet weak var textf1: UITextField!
#IBOutlet weak var textf2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textf.delegate = self
textf1.delegate = self
textf2.delegate = self
// 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 textf1(sender: AnyObject) {
let result = (textf.text! as NSString).doubleValue * (textf2.text! as NSString).doubleValue
textf1.text = String(format:"%.2f", result)
}
#IBAction func segmentedcontrolAction(sender: AnyObject) {
if(segmentedcontrol.selectedSegmentIndex == 0)
{
textf2.text = "5";
}
else if(segmentedcontrol.selectedSegmentIndex == 1)
{
textf2.text = "10";
}
else if(segmentedcontrol.selectedSegmentIndex == 2)
{
textf2.text = "15";
}
}
#IBAction func segmentedcontrolAction(sender: AnyObject)
{
if(segmentedcontrol.selectedSegmentIndex == 0)
{
textf2.text = "5";
}
else if(segmentedcontrol.selectedSegmentIndex == 1)
{
textf2.text = "10";
}
else if(segmentedcontrol.selectedSegmentIndex == 2)
{
textf2.text = "15";
}
let result = (textf.text! as NSString).doubleValue * (textf2.text! as NSString).doubleValue
textf1.text = String(format:"%.2f", result)
}

this class is not key value coding-compliant for the key EventCreate

I'm new to Swift and iOS development. I'm trying to load a secondary view controller as an overlay over a mapView, and when I try to do it I run into the error listed in the title. I'm stumped.
My code is as follows:
// mainMapViewController.swift
import UIKit
import MapKit
import CoreLocation
var events = [Event]()
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UIGestureRecognizerDelegate {
#IBOutlet weak var mapView: MKMapView!
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let locationManager = CLLocationManager()
#IBAction func addEvent(mylongpress: UIGestureRecognizer) {
if mylongpress.state == UIGestureRecognizerState.Began {
let touchpoint = mylongpress.locationInView(mapView)
let newcoord = mapView.convertPoint(touchpoint, toCoordinateFromView: mapView)
let pin = MKPointAnnotation()
pin.coordinate = newcoord
let eventcreatevc = mainStoryBoard.instantiateViewControllerWithIdentifier("EventCreate") as! EventCreate
eventcreatevc.modalPresentationStyle = .OverCurrentContext
self.presentViewController(eventcreatevc, animated: true, completion: nil)
//events.last!.annotation = pin
//events.last!.annotation.title = events.last!.eventName
//pin.title = events.last!.annotation.title
if events.isEmpty {
pin.title = "this is a test"
}
self.mapView.addAnnotation(pin)
print("added pin to map")
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.07, longitudeDelta: 0.07))
self.mapView.setRegion(region, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
let longpress = UILongPressGestureRecognizer(target: self, action: "addEvent:")
mapView.addGestureRecognizer(longpress)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EventCreate" {
var eventcreatevc = segue.destinationViewController as! EventCreate
}
}
override func viewWillAppear(animated: Bool) {
if events.isEmpty {
return
}
else {
for listofevent in events {
let pin = listofevent.annotation
self.mapView.addAnnotation(pin)
}
return
}
}
}
and
// EventCreate.swift
import UIKit
import MapKit
import CoreLocation
class EventCreate: UIViewController, UITextFieldDelegate, MKMapViewDelegate, UIGestureRecognizerDelegate {
// MARK: Properties
var name: String = ""
var loc: String = ""
var cost: Int = 0
var date: String = ""
var annot: MKPointAnnotation = MKPointAnnotation()
#IBOutlet weak var datePicker: UIDatePicker!
#IBOutlet weak var costSlider: UISlider!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var costLabel: UILabel!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var eventNameLabel: UILabel!
#IBOutlet weak var createButton: UIButton!
// MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
createButton.enabled = false
}
func checkValidTextEntry(textField: UITextField) {
let text = textField.text ?? ""
createButton.enabled = !text.isEmpty
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// hides the keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
if textField == nameTextField {
checkValidTextEntry(textField)
name = textField.text!
}
else if textField == locationTextField {
loc = textField.text!
}
}
func setAnnotation(annot: MKPointAnnotation) {
self.annot = annot
}
// MARK: Initialization
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
locationTextField.delegate = self
checkValidTextEntry(nameTextField)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if createButton === sender {
let event = Event(eventName: name, location: loc, cost: cost, date: date, annotation: annot)
events.append(event!)
}
}
}
Any help would be greatly appreciated!

Arrays in Swift - How to add images

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

How to add to UIStepper value with other buttons?

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

Resources