Ser*_*geH 8 function ios swift
在我的应用程序中我有几个场景,每个都显示不同UIAlertController,所以我创建了一个显示此警报的功能,但我似乎无法在"okAction"内调用self.Function.我收到这个错误:
类型的值
'ViewController'没有成员'doAction'
这是代码:
func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : () )
{
let refreshAlert = UIAlertController(title: titleOfAlert, message: messageOfAlert, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.doAction()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) {
UIAlertAction in
}
refreshAlert.addAction(okAction)
refreshAlert.addAction(cancelAction)
self.presentViewController(refreshAlert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
这是我正在调用的函数之一:
func changeLabel1()
{
label.text = "FOR BUTTON 1"
}
Run Code Online (Sandbox Code Playgroud)
我怎么解决呢?
luk*_*302 14
删除self前面的,doAction()因为你没有在对象self上调用动作.
如果你这样做,编译器会告诉你
Invalid use of '()' to call a value of non-function type '()'.情况就是这样,因为doAction没有功能而是空元组.函数具有输入参数和返回类型.因此,类型doAction应该是() -> Void- 它不需要输入和返回Void,即不返回任何东西.
代码应该是这样的:
func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : () -> Void ) {
...
let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) { action in
doAction()
}
...
}
Run Code Online (Sandbox Code Playgroud)
如果要将方法传递action给doAction方法,则必须将类型更改为(UIAlertAction) -> Void并通过它调用doAction(action).