繁体   English   中英

Swift - 类型的值ViewController没有成员* functionName *

[英]Swift - Value of Type ViewController has no member *functionName*

在我的应用程序中我有几个场景,每个场景都显示不同的UIAlertController ,所以我创建了一个显示此警报的函数,但我似乎无法在“okAction”中调用self.Function。 我收到这个错误:

'ViewController'类型'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)
}

这是我正在调用的函数之一:

func changeLabel1()
{
    label.text = "FOR BUTTON 1"
}

我怎么解决呢?

  1. 删除doAction()前面的self ,因为你没有在对象self上调用该操作。

  2. 如果你这样做,编译器会告诉你
    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()
    }
    ...
}

如果你想在通过actiondoAction方法,你将不得不类型更改为(UIAlertAction) -> Void ,并通过调用它doAction(action)

从您的代码中, doAction是函数showAlertController的第三个参数。

首先:更改doAction :() to doAction :() - >()这意味着doAction是一个没有参数和空返回的Closure

第二:调用不应该是self.doAction()而只是doAction()因为它是一个参数而不是一个实例变量

我认为指定闭包的正确方法是这样的:

func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : (() -> Void) ){

   // and then call it like that
   doAction()

}

这里的关键是你不能调用this.doAction()因为传递给函数的参数不是控制器上的属性,对吧?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM