I am Currently working on a swift project in XCode, and I've encountered an issue where I cannot increment an array's one element by through various endeavours.
My ViewController.Swift
import UIKit
class FailureViewController: UIViewController {
#IBOutlet weak var failFactLabel: UILabel!
let failFact = Failure()
override func viewDidLoad() {
super.viewDidLoad()
failFactLabel.text = failFact.failArray[0]
}
#IBAction func showFunFact() {
//this is where the issue is
}
}
For the function showFunFact I have previously tried
for var x = 0; x < failArray.cout; x++ {
failFactLabel.text = failFact.failArray[x]
}
but encountered the error: "Use of Unresolved Identifier".
Putting this aside, I decided to use
for var x = 0; x < 10; {
x+=1
}
Although this does not generate an error however, I see it stops at the first element in my array. I tried +=5 and it displays the 5th element in my array once, I believe this code runs through once. I need it to be a consistently working piece so it continuously displays the next element, I am stumped because this should theoretically work since it is called a "Loop" Any help or suggestion is Appreciated!
Objective Redefined:
I am trying to show one fact at a time, before this I have used a random function to generate a random fact every time however things tend to get repetitive and therefore I decided to start on the initial array index is 0 and grab the next fact (next element in array) every time the button is pressed (Thanks to Luk's Question)
You need to create an instance variable to hold the current factIndex, if that is what you actually are trying:
import UIKit
class FailureViewController: UIViewController {
#IBOutlet weak var failFactLabel: UILabel!
var factIndex = 0
let failFact = Failure()
override func viewDidLoad() {
super.viewDidLoad()
failFactLabel.text = failFact.failArray[factIndex]
}
#IBAction func showFunFact() {
factIndex++
if factIndex >= failFact.failArray.count then {
factIndex = 0
}
failFactLabel.text = failFact.failArray[factIndex]
}
}
Related
Beginner Here,
I'm coding a project that randomly matches up DOTA 2 heroes.
I'm currently pulling the hero image into the ImageViews from the fighters array using Int.random.
However, I'm now trying to implement a corresponding label underneath the image to display the name of the hero currently in the ImageView.
I'm initially trying to do this for fighterOne at fighters["1"] which would be Dragon Knight.
I've tried various 'if' statements, none of which seem to work. I've also scoured forums and documentation, but can't find the solution anywhere.
#IBOutlet weak var fighterOne: UIImageView!
#IBOutlet weak var matchButton: UIButton!
#IBOutlet weak var fighterOneName: UILabel!
let fighters = ["1","2","3","4","5","6","7","8","9","10","11","12",]
var randomIndex1: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
updateFighterName()
updateFighters()
}
///// FUNCTIONS /////
func updateFighterName() {
if fighterOne.image == UIImage(named: "1") {
fighterOneName.text = "Dragon Knight"
} else {
fighterOneName.text = "Wrong"
}
}
func updateFighters() {
randomIndex1 = Int.random(in: 0...11)
fighterOne.image = UIImage(named: fighters[randomIndex1])
}
I can't make sense of the result I'm getting from this. When I run the app, the "Dragon Knight" is occasionally displayed, however, it's not under the correct hero image, it's very erratic as to when it's displayed, and there appears to be no logical display sequence from what I can tell.
Any help would be appreciated and let me know if you need more information!
You need to call updateFighters() before calling updateFighterName() inside your viewDidLoad() because you depend on what it does.
Your viewDidLoad() should look like this:
override func viewDidLoad() {
super.viewDidLoad()
updateFighters()
updateFighterName()
}
And you need to replace:
if fighterOne.image == UIImage(named: "1") {
}
With:
if fighterOne.image.isEqual(UIImage(named: "1")) {
}
I am completely new to coding.
I started using this app called MIMO and learned a few bits and pieces. In one chapter they let us code a simple "dice app" where by pressing a button a number from 1 - 6 appears. Now I wanted to rewrite that so that at the button press the app displays a quote from a predetermined array.
I am completely stuck, however.
Here's what I got:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var quotesLabel: UILabel!
let quotes = ["Quote1!", "Quote2!"]
let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
let randomQuote = quotes[randomIndex]
print(array[randomIndex])
override func viewDidLoad() {
super.viewDidLoad()
}
}
Basically any arbitrary code must be run in a method, in this case in an IBAction which is triggered when the button is pressed. The method viewDidLoad is not needed.
Change the code to
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var quotesLabel: UILabel!
let quotes = ["Quote1!", "Quote2!", "Quote3!", "Quote4!"]
#IBAction func showRandomQuote(_ sender : UIButton) {
let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
let randomQuote = quotes[randomIndex]
quotesLabel.text = randomQuote
}
}
In Interface Builder drag a button into the canvas of the view controller
Connect (⌃-drag) the button to the IBAction and the label to the IBOutlet
Run the app and press the button
I wrote a Model file for my basic app and I'm in the process of applying the model to the UI. It has 3 manual inputs and a text area for the "results" once the calculate button has been pressed.
I'm really struggling with making the UI do what I want it to do, I just want the results displaying, I tried print() but get unresolved identifiers in view controller.
How do I get the .value of my results from the Model file in the view controller? Or have to initialize those again?
Model File (Struct)
struct FuelMaths {
var rate: Double = 3.7 //set initialValvue
var tank: Int = 110
var laps: Int = 13
var totalFuel: Double
var totalStops: Double
init (rate: Double, tank: Int, laps: Int) {
self.rate = rate // declare an instance
self.tank = tank
self.laps = laps
totalFuel = rate * Double(laps)
totalStops = totalFuel / Double(tank)
}
func result () {
print(totalFuel.value)
print(totalStops.value)
}
}
View Controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var rate: UITextField!
#IBOutlet weak var laps: UITextField!
#IBOutlet weak var tank: UITextField!
let calculate = FuelMaths(rate: 3.7, tank: 110, laps: 13)
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 calculate(sender: UIButton) {
}
#IBOutlet weak var display: UITextView!
}
Thanks all.
(Edit: I originally said you didn't instantiate the model at class scope; you did, but you misnamed it as a verb calculate rather than a good noun like fuelCalculationModel. But anyway, I'm using it the way you've written it: which is as sort of a one-off where the values are passed in at construction time and those values are assumed final so that the result is calculated immediately. It is possible to write a model that is designed to persist and adjust to changes in its source value over time, but you need to understand property observers or computed properties for that.)
See if the solution is helpful:
#IBAction func calculate(sender: UIButton) {
if let rateVal = Double(rate.text!),
tankVal = Int(tank.text!),
lapVal = Int(laps.text!) {
let fuelModel = FuelMaths(rate: rateVal, tank: tankVal, laps: lapVal)
display.text = "Total fuel: \(fuelModel.totalFuel) Total Stops: \(fuelModel.totalStops)"
}
else {
display.text = "One of the text fields did not have a valid number."
}
}
Ultimately you want the model to be a persistent object at class-level scope, not function scope, and you want it to recalculate its results whenever its source values are changed, but wait on that until you understand this, especially if-let when constructing numbers out of parsed Strings.
I made an app where I save a label that I can make it go up or down one number in my app. But if I lose out of my app and open it back up, if i make the label go up again than it resets back to zero and goes to one. This is because I have to set the variable value to zero. Here is my code:
#IBOutlet var goal: UILabel!
#IBAction func player1button(sender: AnyObject)
{
NSUserDefaults.standardUserDefaults().setValue(goal.text!, forKey:"firstGoal")
}
var goal1 = 0
#IBAction func goalUp(sender: AnyObject)
{
goal1++
goal.text = "\(goal1)"
}
override func viewDidLoad()
{
super.viewDidLoad()
goal.text = (NSUserDefaults.standardUserDefaults().objectForKey("firstGoal") as? String)
}
Im saving the goal number then calling it back later in the text. Please show me a way to fix it so it just adds on to the previous number.
in viewDidLoad() add
goal1 = Int((NSUserDefaults.standardUserDefaults().objectForKey("firstGoal") as? String)!)
this will set the int variable you are using to keep track of the goals to the correct value when the app loads. currently you are only setting the text label to the correct value.
or you can simply make var goal1 a global variable , just after the imports and before the class keyword , in case you don't need to keep the data till the next time you open the app itself
I am trying to change the value of a variable in Xcode 7 with Swift. For some strange reason, it just doesn't work.
Here are the functions I used.
#IBAction func ten(sender: AnyObject) {
var percentage = 0.10
print("test")
}
#IBAction func twentyBtn(sender: AnyObject) {
var percentage = 0.20
}
#IBAction func fifteenBtn(sender: AnyObject) {
var percentage = 0.15
}
#IBAction func twentyfiveBtn(sender: AnyObject) {
var percentage = 0.25
}
#IBAction func thirtyBtn(sender: AnyObject) {
var percentage = 0.30
}
Then later in the code I use the percentage variable in this function.
#IBAction func calcTip(sender: AnyObject) {
var billAmount: Int? {
return Int(billField.text!)
}
var tipTotal = percentage * Double((billAmount)!)
toalLabel.text = String(tipTotal)
testLabel.text = String(percentage)
}
I don't understand why this shouldn't work because I also have this variable underneath my outlets where at the beggining of the code.
What's even more confusing is that if I try to see if it the button would print into the output, as you see I've tried for the one of the buttons, IT WORKS. Even trying to change the text within a label works, but for some strange reason it won't change a variable.
I'm not sure if this could be a bug with Xcode either.
Declare and initialize your percentage variable outside of your IBAction functions.
Like Mukesh already explained in the comments, if you are writing var percentage = 0.10 within one of these functions, you are not assigning 0.10 to the correct variable. Instead, you are creating a new variable within the scope of that function.
Any code written outside of that function cannot access it, and unless you are returning this value or passing it to a different function, the variable will be deleted by the garbage collector after the program finishes executing that function (so pretty much immediately).
Long story short, your code should look something like this instead:
var percentage = 0;
#IBAction func ten(sender: AnyObject) {
percentage = 0.10
print("test")
}
#IBAction func calcTip(sender: AnyObject) {
var billAmount: Int? {
return Int(billField.text!)
}
var tipTotal = percentage * Double((billAmount)!)
toalLabel.text = String(tipTotal)
testLabel.text = String(percentage)
}