是的,它可以做到。你应该做的是,
注意 - 在我开始之前,这里的代码未经测试,因此您必须进行更改以满足您的需要
- 有一个数组来保存图像,如下所示
var imageArray: [UIImage] = [] // count is 0
- 有 2 个自定义
UICollectionViewCell,一个带有将显示图像的 UIImageView,另一个带有“UIButton. For the cell with the UIImage”,添加以下行以禁用用户交互
.
cell.isUserInteractionEnabled = false
cell.selectionStyle = .none
- 完成上述所有操作后(创建一个数组来保存图像,创建 2 个自定义
UICollectionViewCells),遵循 UICollectionViewDataSource 和 UICollectionViewDelegate 如下所示
class ViewController: ViewController, UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count + 1
//Add + 1 so that there will always be atleast on cell, which will be your button cell
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// This will show the button cell if the condition is met
// If not, it will show the image cell
if indexPath.row == imageArray.count - 1 || indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCell", for: indexPath) as! ButtonCell
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
// Setting image to the cell
cell.image = imageArray[indexPath.row - 1]
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// This condition will make sure that the Button cell is the only one that
// invokes showImagePicker() when you click on any cell
if indexPath.row == imageArray.count - 1 {
showImagePicker()
}
}
}
请注意,我在项目数中添加了+1。即始终显示带有按钮的单元格,因为它始终会显示至少 1 个单元格。
另一件事是使单元格出列,您必须添加一些条件来显示按钮单元格或图像单元格。
- 最后一步是使用
UIImagePickerController 从图库中获取图像,将其添加到数组中,最后调用collectionview.reloadData() 方法重新加载您的收藏视图。如果你想要一个好的资源来了解 UIImagePickerController,请查看 THIS TUTORIAL 上的 Hacking with Swift