2017-04-24 72 views
0

我目前有一个函数,它从数据库收集一个时间并返回给其他函数使用。它需要一个参数,该参数存储在应用程序的另一部分中,以便从数据库中收集值。IBAction函数上的多个参数

我想在IBAction函数中调用这个函数时出现问题。

这里是我的功能代码:

func getDBValue(place: GMSPlace) -> Int { 

    var expectedValue = 0 

    databaseRef.child("values").child(place.placeID).observe(.value, with: { (snapshot) in 
     let currentValue = snapshot.value as? [Int] 

     if currentValue == nil { 
      self.noValue() 
      expectedValue = 0 
     } else { 
      let sumValue = currentValue?.reduce(0, +) 

      let avgValue = sumValue!/(currentValue?.count)! 

      print("The current value is \(String(describing: avgValue))") 

      expectedValue = avgValue 

      self.valueLabel.text = String(describing: avgValue) 
     } 

    }) 

    print("This is the expected WT: \(expectedWaitTime)") 

    return expectedValue 

} 

这里是我是在以多参数的问题我IBAction为功能代码:

@IBAction func addValuePressed(_ sender: Any, place: GMSPlace) { 

    print("This is the place ID: \(place.placeID)") 

    var expectedValue = getDBValue(place: place) 

    expectedValue = expectedValue + 1 

    print("The expectedValue is now: \(expectedValue)") 

    self.valueLabel.text = String(describing: expectedValue) 

} 

这给了我一个libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)错误。经过一些测试后,似乎该错误是由我的IBAction函数中添加的参数place: GMSPlace造成的。有关如何解决这个问题的任何想法?

+0

您不能将参数添加到IBAction。期。根据您的需要,常用的解决方法是(1)使用标签属性(它是一个'Int')来指示哪个发件人被调用,或者(2)使您的'GMSPlace'实例在IBAction中可用。 – dfd

回答

4

IBAction方法不能有任意的签名。你不能在这里添加一个额外的参数。没有办法让按钮发送给你(这个按钮怎么知道place是什么?)通常这是通过只有一个UI元素指向这个动作来处理的(所以你知道按了什么按钮),或者使用tag在发件人识别它。每个视图都有一个tag属性,它只是一个整数。您可以在Interface Builder或代码中设置它,然后您可以阅读它来识别发件人。

首先阅读文档中的Target Action,这些文档解释了它如何在各种平台上工作。在一般情况下,一个IBAction的签名必须是:

@IBAction func action(_ sender: Any) 

然而,在iOS上,也可能是:

@IBAction func action(_ sender: Any, forEvent: UIEvent) 

正如泰勒米以下所指出的,你也可以使用这个签名(尽管如果iOS能够在iOS之外工作,我不会记得它;我只是亲自在那里使用它)。

@IBAction func action() 

但就是这样。没有其他允许的签名。

+1

您也可以拥有'@IBAction func doSomething()'而不带任何参数。 –

+0

在Xcode 9.2/iOS 11.2中,以下签名也可以工作:1)'@IBAction func doStuff(_ sender:UIButton)',即参数的类型可以是实际控件的类型 - 类型没有成为任何。 2)'@IBAction func doStuff(sender:Any)' - 在ViewController的Connections Inspector中,方法名将被列为doStuffWithSender :. – 7stud