2017-09-28 47 views
1

我想在用戶點擊按鈕的時候將節的數量加1,但我不知道該如何將它寫入代碼。Xcode Swift Collection View:如何在點擊按鈕時在節中添加項目數量?

@IBAction func myButton(_ sender: Any) { 

    let numberOfItemsInSection + 1 //What's the correct way to write this line of code? 
} 


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
return 0 // +1 whenever the button gets tapped 
} 
+0

使用一個變量並返回它'numberOfItemsInSection'功能......要添加然後只需+1並重新載入表 – Tj3n

回答

0

這是典型的有一個陣列使用UITableView & UICollectionView時。並且要用對象填充數組。在你的情況下,對象將是Item類型。

var items = [Item]() 

@IBAction func myButton(_ sender: Any) { 
    items.append(Item()) 
    collectionView.reloadData() 
} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return items.count 
} 
+0

感謝時!有效!你嚇壞了! –

+0

沒問題! @ Felix'sHotDogBoss – Jevon718

0

請檢查:

var numberOfItemsInSection = 0 

@IBAction func myButton(_ sender: Any) { 
    numberOfItemsInSection += 1 
    yourcollectionview.reloadData() 
} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return numberOfItemsInSection 
} 
相關問題