I want the code to start a var num = 0. Then after every button hit num increases by 1. The problem that I am running into is that when I switch view controllers and come back to this one it starts at 0 again. Num can only starts at 0 one tie when is loaded for the first time. I want to use userdefults to save the number so no matter what the score will always increase.
import UIKit
class ViewController: UIViewController {
var num = 0
let defaults = UserDefaults.standard
#IBAction func press () {
num += 1
defaults.set(num, forKey: "num")
}
}
You have to initialize num from UserDefaults.
Add this to viewDidLoad:
num = defaults.integer(forKey: "num")
Or simply update your var num = 0 line to:
var num = UserDefaults.standard.integer(forKey: "num")
You can't use your defaults variable in this case.
Call synchronize() immediately after your set data in user defaults, so it save it.
set already set value back to num in View Will Appear as View Will Appear will be called on Pop to this View from other Screen.
See Code
import UIKit
class ViewController: UIViewController {
var num = 0
let defaults = UserDefaults.standard
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
num = defaults.integer(forKey: "num")
print("Value of number from defaults \(num)")
}
#IBAction func press () {
num += 1
defaults.set(num, forKey: "num")
defaults.synchronize()
}
}
I am wondering how to make just 1 view terminate in iOS. I am making an app such that in the viewDidLoad() it generates 52 random strings and appends them to an array. I have it so that when you shake the device, it will perform a segue.
The problem with this is that it keeps the items in the array that I mentioned earlier. This means that when it does the user goes into that view again, it will still have the 52 random strings, plus when it goes through the viewDidLoad function, it will append 52 more strings, so if the user doesn't terminate the whole entire app, but just segues out of the view and goes back in, there will be 104 strings and not 52.
I don't want the above to happen in my app, so I am wondering how you could just terminate this one view while also performing a segue so that this problem won't happen.
Here is some code from my app:
These are the arrays I had:
var theCardsTopPlayerHas = [""]
var theCardsBottomPlayerHas = [""]
var theCardsThatWork = ["2_of_clubs", "2_of_diamonds", "2_of_hearts", "2_of_spades", "3_of_clubs", "3_of_diamonds", "3_of_hearts", "3_of_spades", "4_of_clubs", "4_of_diamonds", "4_of_hearts", "4_of_spades", "5_of_clubs", "5_of_diamonds", "5_of_hearts", "5_of_spades", "6_of_clubs", "6_of_diamonds", "6_of_hearts", "6_of_spades", "7_of_clubs", "7_of_diamonds", "7_of_hearts", "7_of_spades", "8_of_clubs", "8_of_diamonds", "8_of_hearts", "8_of_spades", "9_of_clubs", "9_of_diamonds", "9_of_hearts", "9_of_spades", "10_of_clubs", "10_of_diamonds", "10_of_hearts", "10_of_spades", "jack_of_clubs2", "jack_of_diamonds2", "jack_of_hearts2", "jack_of_spades2", "queen_of_clubs2", "queen_of_diamonds2", "queen_of_hearts2", "queen_of_spades2", "king_of_clubs2", "king_of_diamonds2", "king_of_hearts2", "king_of_spades2","ace_of_clubs", "ace_of_diamonds", "ace_of_hearts", "ace_of_spades"]
Here is what the viewDidLoad method has:
struct shuffledVar {
static var shuffled = [String]();
}
override func viewDidLoad() {
super.viewDidLoad()
upperLabelNumber.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
//MARK: - Shuffling Cards
for _ in 1...52 {
let shuffledCardList = Int(arc4random_uniform(UInt32(theCardsThatWork.count)))
let the_card = theCardsThatWork[shuffledCardList]
print("\(the_card)")
shuffledVar.shuffled.append(the_card)
theCardsThatWork.remove(at: shuffledCardList)
print("Finished Card")
}
theCardsTopPlayerHas = Array(shuffledVar.shuffled[0...25])
theCardsBottomPlayerHas = Array(shuffledVar.shuffled[26...51])
print("")
print(shuffledVar.shuffled)
print("")
print(theCardsTopPlayerHas)
print("")
print(theCardsBottomPlayerHas)
}
This is the code that segues the view:
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
performSegue(withIdentifier: "friendToDashboard", sender: self)
}
Thank you!
The problem is that you are using a static var to store your array of strings.
To solve this problem there are several solutions depending on what you need. Here there are a couple of solutions:
Solution 1
If you really need to keep the shuffled array as a Singleto, then you can empty the shuffled array in the viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
shuffledVar.shuffled = []
upperLabelNumber.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
...
}
Solution 2
If you do not need to keep the shuffled array as a Singleton, then you can modify it as follows:
struct shuffledVar {
var shuffled = [String]();
}
var shuffled = shuffledVar()
override func viewDidLoad() {
super.viewDidLoad()
upperLabelNumber.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
//MARK: - Shuffling Cards
for _ in 1...52 {
let shuffledCardList = Int(arc4random_uniform(UInt32(theCardsThatWork.count)))
let the_card = theCardsThatWork[shuffledCardList]
print("\(the_card)")
shuffled.shuffled.append(the_card)
theCardsThatWork.remove(at: shuffledCardList)
print("Finished Card")
}
theCardsTopPlayerHas = Array(shuffled.shuffled[0...25])
theCardsBottomPlayerHas = Array(shuffled.shuffled[26...51])
print("")
print(shuffled.shuffled)
print("")
print(theCardsTopPlayerHas)
print("")
print(theCardsBottomPlayerHas)
}
You are using static var shuffled so you are using static variable. Do you really need a static variable? If not instead of:
struct shuffledVar {
static var shuffled = [String]();
}
use:
var shuffled:[String] = []
and then in code use:
shuffled.append(the_card)
But if you need this variable to be static (for example you are using it in some other view controller) just remove all elements before adding a new one:
//MARK: - Shuffling Cards
shuffledVar.shuffled.removeAll()
You can read more about static vars https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html and more about arrays: https://developer.apple.com/documentation/swift/array
I'm trying to make an app that lets users input 4 numbers and display what cellular network is that number. Is there a way to automatically display the numbers in the label after the user inputs the numbers without clicking a button? I actually have a code that lets the user input the number but the user must click the enter button for it to display the result on the label. Is there a way for it to automatically display the result? By the way, I'm actually new to swift so I apologize. Here is the code:
import UIKit
import Firebase
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
#IBOutlet weak var numField: UITextField!
#IBOutlet weak var answerField: UILabel!
#IBAction func enterButton(sender: AnyObject) {
matchNumber()
}
func matchNumber(){
let number: String = numField.text!
let numRef = Firebase(url: "https://npi2.firebaseio.com/num_details")
numRef.queryOrderedByKey().observeEventType(.ChildAdded, withBlock: { snapshot in
let network = snapshot.value as! String!
if snapshot.key == self.numField.text! {
self.answerField.text = network
}
else {
self.answerField.text = "Missing"
}
})
}
Add a target to your numField, something like this...
override func viewDidLoad() {
super.viewDidLoad()
self.numField.addTarget(self, action: "editingChanged:", forControlEvents: .EditingChanged)
}
This will trigger the editingChanged method every time a character changes in the numField.
func editingChanged(textField:UITextField) {
if let text = textField.text {
if text.characters.count == 4 {
matchNumber()
}
}
}
Finally we check if there is a string in the input and if it is 4 characters long before running the matchNumber method.
You could use the didSet method.
var numberstring = String() {
didSet {
yourlabel.text = numberstring
}
}
If you are using textfield to take input then you can use textfieldDidEndEditing delegate method.
Count point in a specific moment when button taped in a new column Parse for example :
#IBAction func nbTapped(sender: AnyObject) {
let PFUser.currentUser()!.objectForKey("buttonpressed") as? Int (buttonpressed)! + 1
}
Should be written as follows:
#IBAction func nbTapped(sender: AnyObject) {
var count = PFUser.currentUser()!.objectForKey("buttonpressed")
PFUser.currentUser()!["buttonpressed"] = count + 1
}
I'm not exactly Swift literate (Obj-C user), but that should work with minimal changes.
I have two files which I am working on for my SpriteKit game: SPSwipes.swift and GameScene.swift.
In my SPSwipes.swift file, inside an SPSwipes class, a variable is triggered by an IBAction.
class SPSwipes: UIViewController {
#IBAction func fiveSwipes(sender: AnyObject) {
var no_of_swipes = 5
}
}
In my GameScene.swift file, an if statement checks what value has been assigned to my variable, and creates an array thereof:
if no_of_swipes == 5 {
var array = Array<UInt32>(count: 5, repeatedValue: 0)
for i in 0 ..< 5 {
array[i] = arc4random_uniform(100)
}
}
I receive this error message:
To 'fix' the problem, I realised that I needed to create an instance of my SPSwipes class, so I added this to my GameScene.swift file:
var swipes = SPSwipes()
And then I changed the if statement to say:
if swipes.no_of_swipes == 5{
...
}
Then I received this error:
As far as I'm aware, I have created an instance of the class correctly, but there is evidently an issue.
Your error is here:
#IBAction func fiveSwipes(sender: AnyObject) {
var no_of_swipes = 5
}
You have created a variable inside the function, therefore the variable doesn't exist outside of the function.
What you want is to have the variable live for as long as an object of the class lives, therefore you need to create the variable one level higher:
class SPSwipes: UIViewController {
var numberOfSwipes = 0
#IBAction func fiveSwipes(sender: AnyObject) {
numberOfSwipes = 5
}
}