[英]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.