2015-08-14 53 views
-1
@IBOutlet var items: [UIButton] 
@IBAction func itemsHidden(sender: UIButton) { 
    sender.hidden = true 
    items.removeAtIndex(sender) 
    } 

你好。SWIFT:“removeAtIndex”不适用于(发件人:UIButton)

例如,我有一些项目。

该代码有错误:“无法用类型(UIButton)的参数列表调用'removeAtIndex'”。 我需要做的是,“removeAtIndex”的作品?

谢谢...

+1

在'removeAtIndex'中,您必须指定要删除的项目的索引。对于'sender'你可以通过'items.indexOf(sender)'找到索引。 – MirekE

+0

@斯巴达克,请在将它们发送到stackoverflow之前自己阅读崩溃描述。 –

回答

4

一个removeAtIndex方法,期望得到一个指数作为参数。 如果你想删除一个对象使用func removeObject(_ anObject: AnyObject)

编辑

在有迅速的阵列(只在NSMutableArray)没有removeObject。 为了删除一个元素,你需要弄清楚它的指数第一:

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

Array类没有'removeObject(:)'方法。 –

+0

@DuncanC谢谢,你是对的。 –

+0

这是工作。非常感谢) – Spartak

0

你不告诉我们班级的items对象。我想这是一个数组。如果没有,请告诉我们。

正如Artem在他的回答中指出的那样,removeAtIndex接受一个整数索引并删除该索引处的对象。索引必须在0到array.count-1之间

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

如果您使用斯威夫特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'."); 
} 

(我还是习惯阅读斯威夫特功能定义包括可选项和参考协议(如Generator),因此上述语法可能不完美。)

+0

项目是数组。 – Spartak

相关问题