2015-10-05 82 views
0

我一直在嘗試從另一個類調用我的函數到我的新類中。 原先的功能代碼和類顯示如下:在Swift中調用另一個類的函數2.1

class ViewController: UIViewController { 

func displayAlert(title: String, message: String) { 

     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) 

     alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in 

     //self.dismissViewControllerAnimated(true, completion: nil) 

     }))) 

     self.presentViewController(alert, animated: true, completion: nil) 

    } 
} 

我試圖調用顯示報警功能在這個類像這樣:

class logInViewController: UIViewController{ 

    var loginError = ViewController().displayAlert("error", message: "What is wrong") 
     print(loginError) 

    or 


    ViewController().displayAlert("error", message: "What is wrong") 

} 

當代碼運行時,它不顯示警報。但是,如果我在從原來的ViewController類的功能塊拖我可以調用

displayAlert("error", message: "Some Message") 

在沒有發出警報大作。不知道我在做什麼錯我已經閱讀了其他堆棧溢出文章,但我仍然遇到同樣的問題,沒有顯示警報。

+0

我很驚訝你沒有得到一個「視圖不在窗口層次結構」錯誤信息作爲線索。 –

回答

2

所以看起來這裏有幾件事情正在進行。

  • 我要去猜測,從ViewController而不是UIViewControllerlogInViewController繼承。如果沒有,它應該。
  • ViewController().displayAlert(...)正在初始化一個ViewController實例,然後在該實例上調用displayAlert(...)。初始化的ViewController實例不在視圖層次結構中,因此警報將不會顯示在任何位置。無論如何你都不應該打電話給ViewController()
  • 只要在前面調用displayAlert(...)而沒有ViewController()就會調用當前視圖控制器的實例方法(self),這是正確的!所以,你應該這樣稱呼它,或者像self.displayAlert(...)(這裏假定logInViewController繼承自ViewController)。
+0

甜甜的男人感謝不能相信我錯過了那個小細節。但那通常會發生什麼,它總是有助於擁有另一雙眼睛。再次感謝 – Rico

相關問題