I'm pretty new to Swift and programming, so this may seem pretty basic, but I haven't been able to locate an answer on StackOverflow or Google while trying to solve this issue today.
I'm create a basic life counter app for fun, but I'm having some trouble when I'm trying to reset the user's life totals. I'm able to add and subtract totals from the starting value, but when I run reset it the initial value is staying in memory.
For example, if player one has 9 life and player 2 has 0, if I hit the reset button both totals will show 10 (the default), however, if I subtract 1 from player 1 it will show 8 and if I added 1 to player 2 it would show 1 instead of 11.
I guess I need to pass the value from reset somehow or just put the default variable somewhere else? Any help is appreciated. Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var playerOneAdd: UIButton!
#IBOutlet weak var playerOneMinus: UIButton!
#IBOutlet weak var playerOneLife: UILabel!
#IBOutlet weak var playerTwoMinus: UIButton!
#IBOutlet weak var playerTwoPlus: UIButton!
#IBOutlet weak var playerTwoLife: UILabel!
#IBOutlet weak var resetButton: UIButton!
var playerOne = 10
var playerTwo = 10
override func viewDidLoad() {
super.viewDidLoad()
playerOneLife.transform = CGAffineTransformMakeRotation(3.14)
}
#IBAction func PlayerOnePlusButton(sender: AnyObject) {
++playerOne
playerOneLife.text = String(playerOne)
}
#IBAction func playerOneMinusButton(sender: AnyObject) {
--playerOne
playerOneLife.text = String(playerOne)
}
#IBAction func playerTwoMinusButton(sender: AnyObject) {
--playerTwo
playerTwoLife.text = String(playerTwo)
}
#IBAction func playerTwoPlusButton(sender: AnyObject) {
++playerTwo
playerTwoLife.text = String(playerTwo)
}
#IBAction func resetPressed(sender: AnyObject) {
var playerOne = 10
var playerTwo = 10
playerOneLife.text = String(playerOne)
playerTwoLife.text = String(playerTwo)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When you call var again, you re-define the variable. You should just set it equal.
playerOne = 10
playerTwo = 10
You need to remove the var keyword in resetPressed:
#IBAction func resetPressed(sender: AnyObject) {
playerOne = 10
playerTwo = 10
playerOneLife.text = String(playerOne)
playerTwoLife.text = String(playerTwo)
}
The var keyword defines a new variable. Since the variables are declared inside of a function, they are local variables and they override the instance variables. Local variables are local to a function, so the overridden variables aren't accessed in the other functions.
Related
I've been trying to address this issue for a few days and it seems I'm only going in circles.
I'm adding data to core data by tapping on tableView cells and then displaying the items on another tableView.
That works great, the problem is this:
When I click on the other table view rows, to be able to see the item with all the other values stored in core data, I get
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the showMeTheGoodiesTwo(entry: myCart) line
...Inside viewDidLoad. But I do not know why that's happening, as the entity is not empty.
Here's the code of the view controller where I want to display the item's details.
Hope somebody can give me a hand.
Cheers!
import UIKit
class productQuantityViewController: UIViewController {
var myCart: Cart!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var productNameLabel: UILabel!
#IBOutlet weak var productDescriptionLabel: UILabel!
#IBOutlet weak var productAmountLabel: UITextField!
#IBOutlet weak var minusButton: UIButton!
#IBOutlet weak var plusButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
productImage.layer.cornerRadius = 10
minusButton.layer.cornerRadius = minusButton.frame.size.width/2
plusButton.layer.cornerRadius = plusButton.frame.size.width/2
showMeTheGoodiesTwo(entry: myCart)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showMeTheGoodiesTwo(entry: Cart) {
let name = entry.product
let quantity = entry.inventory
let description = entry.productDescription
let image = entry.productImage as Data?
let xNSNumber = quantity as NSNumber
productNameLabel!.text = name
productDescriptionLabel!.text = description
productAmountLabel!.text = xNSNumber.stringValue
productImage!.image = UIImage(data:image!)
print(productNameLabel.text as Any)
}
}
You need to change
var myCart: Cart!
To
var myCart: Cart?
? is use to make it optional.
And in viewDidLoad use
if (myCart != nil){
showMeTheGoodiesTwo(entry: myCart)
} else {
//do something.
}
instead of
showMeTheGoodiesTwo(entry: myCart)
I'm a newbie to swift and for now it's a pain in the a$$ to code.
I'm trying to make a very simple app where the user enters a number to a textfield
and then when a button is clicked it shows the number + 1 in a label.
I always get this error:
Thread 1:EXC_BREAKPOINT (code=1, subcode=0x1002c11ec)
This is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var tav: UITextField!
#IBOutlet weak var fogy: UITextField!
#IBOutlet weak var ar: UITextField!
#IBOutlet weak var eredmeny: UILabel!
#IBOutlet weak var szamolasBtn: UIButton!
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 szamol(_ sender: Any) {
let number = Int(tav.text!)! + 1
eredmeny.text = String(describing: number)
}
}
I ran your code and it works fine if an integer in entered in the textfield. But if you enter any character other than a string then the app crashes because Int(tav.text!)! returns nil and adding 1 to nil. Check for nil first and then add something to it.
I need the stepper and label to reset back to 0 at the same time that my variables reset. The problem is the steppers and labels are in a different class and are not resetting when the variables do. I tried using delegates(if someone can show me the best way that would be great) instead of an instance of my view controller, but I can't get anything to work. Thanks for any help in advance.
ViewController:
class ViewController: UIViewController
{
var colors = CircleView()
#IBOutlet weak var circleView1: CircleView!
#IBOutlet weak var blueStepper: UIStepper!
#IBOutlet weak var greenStepper: UIStepper!
#IBOutlet weak var redStepper: UIStepper!
#IBAction func stepperChange(sender: UIStepper)
{
circleView1.redd1 = Int(redStepper.value);
redValue.text = Int(sender.value).description;
}
#IBAction func stepperChange1(sender: UIStepper)
{
circleView1.greenn1 = Int(greenStepper.value);
greenValue.text = Int(sender.value).description;
}
#IBAction func stepperChange2(sender: UIStepper)
{
circleView1.bluee1 = Int(blueStepper.value);
blueValue.text = Int(sender.value).description;
}
}
UIView:
class CircleView: UIView
{
var colors1=ViewController()
func updateStepper
{
if(redd1==Int(red1)&&greenn1==Int(green1)&&bluee1==Int(blue1))
{
redd1=0;
greenn1=0;
bluee1=0;
colors1.redStepper.value=0.0;//
colors1.greenStepper.value=0.0;//
colors1.blueStepper.value=0.0;//
}
}
}
I do not quite understand your code, like the "if" condition in your CircleView, the lack of parameters to the method "updateStepper". I am assuming you just wrote some "swift-pseucode" and I will ignore some parts of it to explain how you could implement a delegate for it. Below is an example code:
import UIKit
protocol CircleViewDelegate: class {
func updateStepper(view: CircleView)
}
class ViewController: UIViewController, CircleViewDelegate{
#IBOutlet weak var circleView1: CircleView!
#IBOutlet weak var blueStepper: UIStepper!
#IBOutlet weak var greenStepper: UIStepper!
#IBOutlet weak var redStepper: UIStepper!
var circleViewDelegate: CircleView!
override func viewDidLoad() {
super.viewDidLoad()
circleViewDelegate = circleView1
circleViewDelegate!.delegate = self
}
func updateStepper(view: CircleView) {
//code you want to execute when you call updateStepper() in the CircleView()
}
}
class CircleView: UIView {
weak var delegate: CircleViewDelegate?
func updateStepper() {
//whenever you want your viewController to updated other views based
//on a condition inside an element like UIView, you can use a delegate
//this way, your code is executed by the ViewController whenever you want
delegate?.updateStepper(self)
}
}
A callback in your UIView must be set to call "updateStepper" when you want. Unfortunately, I didn't quite understand the time it should be called according to your question.
I hope this helps!
Have you tried NSNotification?
If it's always going to reset to zero, then create a func without the if statement in CircleView:
func resetStepper(not: NSNotification) {
r1 = 0
g1 = 0
b1 = 0
c1.rStep.value = 0.0
c1.bStep.value = 0.0
c1.gStep.value = 0.0
}
Also in CircleView's createView func, add:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resetStepper:", name: "ResetStepper", object: nil)
Then in the view controller, post a notification from whichever button is calling it.
#IBAction func callReset(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("ResetStepper", anObject: nil)
}
That will send the notification that CircleView is listening for to call the function.
Hope that works for you.
Im doing this wrong I but I'm not sure how to get it I could really use some help. I have 3 sliders (I may need more later) and basically they are 1-10 in value kinda for a rating system and i want them averaged to create an average score.. so this is what I have
#IBOutlet weak var speed: UISlider!
#IBAction func speedChange(sender: AnyObject) {
let speedValue = speed.value
}
#IBOutlet weak var body: UISlider!
#IBAction func bodyChange(sender: AnyObject) {
let bodyValue = body.value
}
#IBOutlet weak var details: UISlider!
#IBAction func detailsChange(sender: AnyObject) {
let detailsValue = details.value
}
#IBOutlet weak var score: UILabel!
func final() {
var thescore = (speed.value + body.value + details.value) / 3
score.text = "\(thescore)"
}
Only problem is it doesn't work. the + errors out, so I need to fix that, but even still i think my methodology is completely off.
It worked for me. Are you sure the outlets in the storyboard are linked to your Controller ?
Also, you may want to call your function final every time a slider changed its value, like this :
#IBOutlet weak var sliderA: UISlider!
#IBAction func sliderAchanged(sender: AnyObject) {
fonction()
}
#IBOutlet weak var sliderB: UISlider!
#IBAction func sliderBchanged(sender: AnyObject) {
fonction()
}
#IBOutlet weak var sliderC: UISlider!
#IBAction func sliderCchanged(sender: AnyObject) {
fonction()
}
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
fonction()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fonction() {
var thescore = (sliderA.value + sliderB.value + sliderC.value ) / 3
label.text = "\(thescore)"
}
And I added a call to the function in viewDidLoad method to initilaize the label's text.
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var labelA: UILabel!
#IBOutlet weak var labelB: UILabel!
var dataPassed:String!
var secondDataPassed:String!
var newVar: String!
var newVar2: String!
override func viewDidLoad() {
super.viewDidLoad()
labelA.text = dataPassed
labelB.text = secondDataPassed
newVar = labelA.text
println(newVar)
}
println(newVar) *** I can't access newVar outside override func viewDidLoad() { - Gives "expected declaration" Its driving me crazy!!!***
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Is there any data in dataPassed? If you don't assign any String to your dataPassed variable, and then you assign newVar to dataPassed, newVar will have nothing to print.
Try:
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var labelA: UILabel!
#IBOutlet weak var labelB: UILabel!
var dataPassed:String! = "Test."
var secondDataPassed:String!
var newVar: String!
var newVar2: String!
override func viewDidLoad() {
super.viewDidLoad()
labelA.text = dataPassed
labelB.text = secondDataPassed
newVar = labelA.text
println(newVar)
}
Secondly, it appears that you're trying to println again outside of the function. That isn't going to work, because viewDidLoad is essentially the "main method" of your app. You can create other functions that respond to button touches, etc... and run a println there, but because Swift code is executed functionally, the code you're executing has to be inside of a particular function. While you can declare variables, as you have, you can't perform actions such as printing them outside of a function, because then there's no order/method to the madness.
The only place where you can run Swift code on a standalone basis without functions is in a Swift Playground. In XCode you can select File -> New -> Playground to try this out.