2017-06-08 23 views
0
func displayalert(title:String, message:String, vc:UIViewController) 
{ 
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in 

     self.dismiss(animated: true, completion: nil) 

    }))) 

    vc.present(alert, animated: true, completion: nil) 


} 


this is the function i have used.i tried to call it like this, 

displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController()) 

它返回错误“不良访问”。 vc.present像循环一样运行。我不明白问题是什么。创建全局显示报警功能,并从任何视图控制器调用它

+0

问题是什么? –

+0

将此方法创建为静态方法,并将其类添加到项目的.pch文件中。你将可以访问任何课程。 – Priyal

+0

这是糟糕的编程习惯。将代码放入'UIViewController'的扩展中,删除'vc'参数并删除'present'行中的'vc.'。 – vadian

回答

0

我运行你的代码,它工作正常。我会在vc中通过自我。

self.displayalert(title: "Title", message: "Some Message", vc: self) 

您也可以UIViewController-

的延伸
extension UIViewController { 
      // Your Function... 
    } 

现在,您可以全局访问任何视图控制器此功能,只需通过typing-

self.displayalert(title: "Title", message: "Some Message", vc: self) 
+0

你也可以做一个UIViewController的扩展,并把你的函数放在那里,这样你就可以从任何视图控制器中全局访问这个函数,只需输入self.displayalert(title:“Title”,message:“Some Message”,vc :self) –

+0

它的工作..非常感谢你兄弟。 – faheem

1

您正在将validateOTPViewController的新实例传递给displayalert函数。

将其更改为:

displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:self) 

这将当前视图控制器传递给函数,而不是尚未提出一个新的。

1

斯威夫特4
使用您的函数创建UIViewController的扩展,以显示具有所需参数的警报ameter参数

extension 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 

      alert.dismiss(animated: true, completion: nil) 

     }))) 

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


     } 
} 


现在从您的视图控制器调用这个函数:

class TestViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.displayalert(title: <String>, message: <String>) 
    } 
} 
相关问题