问题描述
我是从头开始快速构建iOS应用程序(使用swift 4)的新手,并且想要执行以下操作.1.在UICollectionView中实现多个单元格选择,2.将选定的单元格数据传递到服务器.请任何人都可以帮助我,该怎么做?告诉我这样做的过程和支持文章.
I'm new to swift and building iOS Application from the scratch (using swift 4) and want to do something like below.1. Implement Multiple cell selections in UICollectionView,2. Pass selected cells data to Server.Please anyone can help me, how to do that? Tell me the process and supporting articles to do that.
下面是参考图像.预先感谢.
Below is reference Image. Thanks in Advance.
推荐答案
这个基本示例.您可以根据自己的数据进行更改.
This basic example. You can change as per your data.
选择任何单元格后,您需要检查是否已选择了选定的单元格.
When you select any cell then you need to check that selected cell is already selected before or not.
如果没有,则在indexArray
中添加选定的单元格indexPath
,并在valueArray
中添加选定的单元格值.
If not then add selected cell indexPath
in indexArray
and selected cell value in valueArray
.
如果先前选择了当前选定的单元格,则从indexArray
中删除indexPath
,还从valueArray
If current selected cell is previously selected then remove indexPath
from indexArray
and also remove selected cell value from valueArray
在continue
按钮上,按arrSelectedData
传递到服务器或下一屏幕.
on continue
button press pass arrSelectedData
to server or next screen.
在3个数组以下定义.
var arrData = [String]() // This is your data array
var arrSelectedIndex = [IndexPath]() // This is selected cell Index array
var arrSelectedData = [String]() // This is selected cell data array
//UICollectionView委托&数据源
//UICollectionView Delegate & DataSource
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
if arrSelectedIndex.contains(indexPath) { // You need to check wether selected index array contain current index if yes then change the color
cell.vw.backgroundColor = UIColor.red
}
else {
cell.vw.backgroundColor = UIColor.lightGray
}
cell.layoutSubviews()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)!")
let strData = arrData[indexPath.item]
if arrSelectedIndex.contains(indexPath) {
arrSelectedIndex = arrSelectedIndex.filter { $0 != indexPath}
arrSelectedData = arrSelectedData.filter { $0 != strData}
}
else {
arrSelectedIndex.append(indexPath)
arrSelectedData.append(strData)
}
collectionView.reloadData()
}
}
这篇关于如何使用Swift 4在UICollection View中获得多个选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!