Xcode Swift Collection View:如何在点击按钮时在节中添加项目数量?

Xcode Swift Collection View:如何在点击按钮时在节中添加项目数量?

问题描述:

我想在用户点击按钮的时候将节的数量加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

这是典型的有一个阵列使用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

请检查:

var numberOfItemsInSection = 0 

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

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