2017-05-31 133 views
0

我在listViewCell.swift和listViewCell.xib中設計了自定義單元格。其中我有textfield。當用戶輸入超過100的數字時,我想顯示警報。 我在HomeViewController中有tableView。在swift中顯示自定義單元格的警報3

let alert = UIAlertController(title: "Error", message: "Please Insert value less than 100", preferredStyle: UIAlertControllerStyle.alert) 
      alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)) 
      UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) 

然後它給了我Attempt to present <UIAlertController: 0x7f945a5a67d0> on <ProjName.LoginController: 0x7f945a407e70> whose view is not in the window hierarchy!

,當我更改代碼以

let alert = UIAlertController(title: "Error", message: "Please Insert value less than 100", preferredStyle: UIAlertControllerStyle.alert) 
      alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)) 
      HomeViewController().present(alert, animated: true, completion: nil) 

然後它給了我unexpectedly found nil while unwrapping an Optional value 並指向 `覆蓋FUNC viewDidLoad中(){ 超。 viewDidLoad()

**tableViewList.delegate = self** 
    tableViewList.dataSource = self 
    searchBar.delegate = self` 

如何顯示來自自定義單元格的警報?或者我們如何在HomeViewController中創建一個通用的提醒函數並將其顯示爲任何swift文件?

在此先感謝

+0

你在哪一行得到這個錯誤? – KKRocks

+0

你的tableview和alert是否在同一個HomeController上?如果是這樣而不是HomeViewController(),爲什麼不嘗試自我。 (alert,animated:true,completion:nil) – Janmenjaya

+0

我在'tableViewList.delegate = self'處得到錯誤 – Kalpesh

回答

1

您可以與您的自定義單元格的代表一起去。將您的自定義單元格的代表設置爲didEnterInvalidValuedidEnterValidValue,並將其設置爲HomeViewController。從這些代表實現中,使用自定義消息顯示您的UIAlertController

或者您可以迭代您的self.navigationController?.viewControllers以查找頂視圖控制器並在該視圖控制器的視圖上顯示UIAlertController

+0

我創建了一個名爲didEnterInvalidValue的代理 增加了'cell.didEnterInvalidValue = self as? customProtocol1'在的tableView cellForRowAt功能 函數外我寫顯示警報功能 'FUNC displayAlert(標題:字符串){ 打印(「這一行打印」) }' 課外我聲明瞭自定義協議來調用功能 '協議customProtocol1 { FUNC displayAlert(標題:字符串) }:在類customProtocol1' 然後我打電話'didEnterInvalidValue .displayAlert(標題' – Kalpesh

+0

在listViewCell.swift 我加入'變種didEnterInvalidValue?: 「Error」)'驗證後 但是仍然沒有執行DisplayAlert功能。你能幫我告訴我哪裏出錯了嗎?我是新來的 – Kalpesh

+0

那麼你需要首先研究它的代表。通過此鏈接: https://code.tutsplus.com/tutorials/swift-from-scratch-delegation-and-properties--cms-23445 –

0

大多數最簡單的將是

第1步:

從您的視圖控制器,你必須使用你的自定義單元格,爲您的文本框的共同委託功能,其目的是通知你有關文本長度。 您可能需要爲此擴展UITextFieldDelegate。

或U可以分配一個目標函數,以您的文本框(不知道它的工作原理雖然)

你如何捕獲特定文本字段?

您需要使用indexPath爲每個textField分配一個標記,並使用該標記捕獲該特定的textField。

第2步:

在此功能,您可以只用

self.present(alert, animated: true, completion: nil) 
0

我會去委託答案顯示您的警報。但是爲了更快的解決方案,在幾個項目中,我在AppDelegate的rootViewController(通常是UINavigationController)中創建一個單例,以便隨時獲得rootController。使用keyWindow,它不是很受推薦,因爲keyWindow並不總是由誰控制的,例如,alert對話框重新定義它。

另一個項目我創建了AlertClass singletone,它由rootController初始化,並且總是從它調用它。

相關問題