k0le
k0le

Reputation: 38

value from func from other viewController

I'm trying to write simple clicker but I have some problem, on "StartViewController" I have func value() it add per sec 1 + click 1 + last save value and I have shopViewController on the shopViewController I have button when I press it it must give +1(every time) to click but how can I access to current value from func value()? When I try get current value I get nil

func value() -> Float {
    let endValue = appPerSec + valueToLoad + click
    valueToSave = endValue
    valueLable.text = "\(endValue)"
    return valueToSave
}

// shopViewController

var StartView:StartViewController!
var currentValue:Float! = 0.0
@IBAction func testAdd(_ sender: Any) {
     currentValue = StartView.value // here I get NIL
     print(currentValue)
}

Upvotes: 0

Views: 48

Answers (2)

Ashish Sharma
Ashish Sharma

Reputation: 663

i did not UnderStand your question but i can give solution in parts for the terms i can read, or please improve your question so that i can understand exactly what you are looking for.

meanwhile i'll just give some concepts that i think you are looking for, if not useful please edit your question before rating not useful :

to make a timer you can use

 @IBOutlet weak var timeInTimer: UILabel!

 var timer = Timer()

@IBAction func buttonPressed(_ sender: Any) //to stop the timer
{
    timer.invalidate()
}

@IBAction func playButtonPressed(_ sender: Any) //to start the timer
{
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processTimer), userInfo: nil, repeats: true)
}

To pass data from one view to other view :

let anyObjectName = storyboard?.instantiateViewController(withIdentifier: "IdentifierOfSecondViewController") as! IdentifierOfSecondViewController
                        anyObjectName.userName = userName //where username is a variable in second view

Upvotes: 1

J Manuel
J Manuel

Reputation: 3070

You can use Delegate and Protocols. Above your shopView add:

protocol ShopProtocol{
    func updateCount();
}

In your shopView add:

var delegateShop:ShopProtocol?

And when you change that variable, go to:

delegateShop.updateCount()

In your main view controller, when you present this shopViewController (before presenting it), add:

shopController.delegateShop = self

And change your ViewController definition to

class ...: UIViewController, ..., ShopProtocol{

And, of course, create in that view controller:

func updateCount(){
 //do Stuff
}

Upvotes: 0

Related Questions