2017-05-31 77 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初始化,并且总是从它调用它。

相关问题