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

8
在我的应用程序中,有几种不同的情景,每种情景都展示了一个不同的 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)
}

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

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

如何解决这个问题?
3个回答

13
  1. doAction()前面删除self,因为你不在对象self上调用该方法。

  2. 如果你这样做编译器会提示错误:
    Invalid use of '()' to call a value of non-function type '()'。因为doAction不是一个函数而是一个空元组。函数应该有输入参数和返回类型。因此doAction的类型应该为() -> Void——它不需要输入任何参数并且没有返回值,也就是什么都不返回。

代码应该像这样:

func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : () -> Void ) {
    ...
    let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) { action in
        doAction()
    }
    ...
}

如果您想将 action 传递给 doAction 方法,您需要将类型更改为 (UIAlertAction) -> Void 并通过 doAction(action) 进行调用。


谢谢!我选择了你的答案,因为它解释得更清楚。 - SergeH

1

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

因此,第一步:将 doAction : () 改为 doAction: ()->()。这意味着 doAction 是一个没有参数和空返回值的 闭包

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


0

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

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

   // and then call it like that
   doAction()

}

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


编辑:还是出现了同样的错误。谢谢您的快速回复(我在编辑出现之前就已经回复了,我会检查它)。 - SergeH
它起作用了。我选择了luk2302的答案,因为它解释了问题所在。不过还是谢谢! - SergeH
@user3902533 不用担心,关键是你解决了问题。我想进一步解释我的答案,但我看到你已经找到了你要找的东西... - the_critic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接