2015-08-14 51 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

相關問題