从 Swift 中的 IBOutletCollection 获取项目

Getting An Item from IBOutletCollection in Swift

我收到一个错误 "Type of expression is ambiguous without more context"

这是我的代码

@IBOutlet var customerDashboardButtons:[NSArray]?

var predicate = NSPredicate(format: "SELF.tag == %d", tag)
var filteredButtons = customerDashboardButtons!.filter { predicate.evaluateWithObject([=11=]) };
if 0 < filteredButtons.count {
      var button = customerDashboardButtons!.first
      button.hidden = true // getting an error in this line as "Type of expression is ambiguous without more context
 }

我尝试了以下方法,

var button:UIButton = customerDashboardButtons!.first //Error "NSArray? is not convertible to UIButton"

var button = customerDashboardButtons!.first as UIButton //Error "NSArray? is not convertible to UIButton"

如有任何帮助,我们将不胜感激。

@IBOutlet var customerDashboardButtons:[NSArray]?

创建数组数组。
调用 customerDashboardButtons!.first 将 return 数组中的第一个数组(NSArray)([…] 也将创建一个数组)

我怀疑您希望 customerDashboardButtonsUIButton 的数组,所以您会使用

@IBOutlet var customerDashboardButtons:[UIButton]?

在这里使用customerDashboardButtons!.first会给你一个UIButton。由于数组的类型是 UIButton,您不必将 button 声明为 UIButton。

  var button = customerDashboardButtons!.first

如果你改变你的数组就会工作。

下面是一个如何创建 IBOutletCollection 并从中获取项目的示例

1) @IBOutlet var simpleTextField: [UITextField]!

2) 从中获取文本文件的示例。

for index in 0...(simpleTextField.count - 1)  {
    let textField : UITextField = simpleTextField[index]
    textField.isUserInteractionEnabled = true
}