【问题标题】:SWIFT: "removeAtIndex" don't work with (sender:UIButton)SWIFT:“removeAtIndex”不适用于(发件人:UIButton)
【发布时间】:2015-08-14 21:05:57
【问题描述】:
@IBOutlet var items: [UIButton]
@IBAction func itemsHidden(sender: UIButton) {
    sender.hidden = true
    items.removeAtIndex(sender)
    }

你好。

例如,我有一个项目数组。

代码出现错误:“无法使用 (UIButton) 类型的参数列表调用 'removeAtIndex'”。 我需要做什么,“removeAtIndex”有效?

谢谢...

【问题讨论】:

  • removeAtIndex 中,您必须指定要删除的项目的索引。对于sender,您可以通过items.indexOf(sender) 查找索引。
  • @Spartak 请在将崩溃描述发送到 stackoverflow 之前自己阅读它们。

标签: ios swift uibutton hidden sender


【解决方案1】:

removeAtIndex 方法期望获得一个索引作为参数。 如果要删除对象,请使用 func removeObject(_ anObject: AnyObject)

编辑

swift 的数组中没有removeObject(仅在NSMutableArray 中)。 为了删除一个元素,你需要先弄清楚它的索引:

if let index = find(items, sender) {
    items.removeAtIndex(index)
}

【讨论】:

  • Array 类没有removeObject(:) 方法。
  • @Spartak 不客气。接受答案怎么样? ;)
【解决方案2】:

您没有告诉我们您的items 对象的类别。

我假设它是一个数组。如果没有,请告诉我们。

正如 Artem 在他的回答中指出的那样,removeAtIndex 采用整数索引并删除该索引处的对象。索引必须介于零和array.count-1

Swift Array 对象没有removeObject(:) 方法,因为数组可以在多个索引处包含相同的条目。您可以使用 NSArray 方法 indexOfObject(:) 来查找对象的第一个实例的索引,然后 removeAtIndex。

如果你使用的是 Swift 2,你可以使用 indexOf(:) 方法,传入一个闭包来检测同一个对象:

//First look for first occurrence of the button in the array.
//Use === to match the same object, since UIButton is not comparable
let indexOfButton = items.indexOf{$0 === sender}

//Use optional binding to unwrap the optional indexOfButton
if let indexOfButton = indexOfButton
{
  items.removeAtIndex(indexOfButton)
}
else
{
   print("The button was not in the array 'items'.");
}

(我仍然习惯于阅读 Swift 函数定义,其中包括选项和引用协议(如 Generator),因此上述语法可能并不完美。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多