Reputation: 311
When a button is pressed in FirstViewController, I would like for it to call a func pressedButton() in another class (SecondViewController). How do I do this?
I've tried the following, and it does not work right:
SecondViewController().pressedButton()
Here's the code for pressedButton:
func pressLearnButton() {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
self.scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0), animated: true)
}
Upvotes: 2
Views: 17597
Reputation: 3917
Syntactically, it seems like you're trying to accomplish what a static method normally does. Unless this is what you're trying to accomplish, and I'm guessing it's not, you need to instantiate your SecondViewController before you call a method on it, assign it to a variable, and call your desired method as follows:
let otherViewController: SecondViewController = SecondViewController()
let result = otherViewController.doSomething()
If you're trying to transition (segue) to another view controller when you click on the button you should be using the prepareForSegue()
method to make the transition to the next view controller. Also, don't forget to set the segue identifier on the Storyboard.
Hopefully this is helpful.
Upvotes: 4
Reputation: 15784
First of all, you have to keep a reference to an instance of SecondViewController in your FirstViewController. Then, in order to call a function foo()
in SecondViewController from your FirstViewController, just call secondInstance.foo()
. If foo() is class function, you can call with SecondViewController.foo().
class A : UIViewController {
var myB = B()
func callBFoo() {
myB.foo()
}
func callStaticBFoo() {
B.staticFoo()
}
}
class B : UIViewController {
func foo() {
println("foo")
}
class func staticFoo() {
println("static foo")
}
}
Upvotes: 0
Reputation: 12677
You really call it. But, in your case, it depends on many factors. Seems it must show anything by calling pressedButton method. Need to declare variable of you controller, add it view to view of your current controller, and you will see visual data.
Upvotes: 0