[英]How do I call a method from another class in Swift?
当在FirstViewController中按下按钮时,我希望它在另一个类(SecondViewController)中调用funcPressedButton()函数。 我该怎么做呢?
我已经尝试了以下方法,但无法正常工作:
SecondViewController().pressedButton()
这是按下按钮的代码:
func pressLearnButton() {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
self.scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0), animated: true)
}
从语法上讲,似乎您正在尝试完成静态方法通常要做的事情。 除非这是您要完成的工作,而且我猜不是 , 否则 ,您需要实例化SecondViewController,然后才能对其调用方法,将其分配给变量,然后按如下所示调用所需的方法:
let otherViewController: SecondViewController = SecondViewController()
let result = otherViewController.doSomething()
如果您在单击按钮时尝试转换(segue)到另一个视图控制器,则应该使用prepareForSegue()
方法转换到下一个视图控制器。 另外,不要忘记在情节提要上设置segue标识符。
希望这会有所帮助。
首先,您必须在FirstViewController中保留对SecondViewController实例的引用。 然后,为了从FirstViewController调用secondInstance.foo()
的函数foo()
,只需调用secondInstance.foo()
。 如果foo()是类函数,则可以使用SecondViewController.foo().
进行调用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")
}
}
你真的叫它。 但是,就您而言,这取决于许多因素。 似乎它必须通过调用按下按钮方法显示任何内容。 需要声明控制器的变量,将其添加到当前控制器的视图中,您将看到可视数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.