在Swift中编程的新手,我的错误是什么原因以及如何解决?非常感谢 .
import UIKit
import Photos
class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource , UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
@IBOutlet weak var myCollectionView: UICollectionView!
var imagesArray = [UIImage]()
override func viewDidLoad(){
super.viewDidLoad()
myCollectionView.delegate = self
myCollectionView.dataSource = self
}
@IBAction func addPhoto(_ sender: AnyObject) {
let picker:UIImagePickerController = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.delegate = self
picker.allowsEditing = false
self.present(picker, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! cell
cell.configurecell(imagesArray[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedimage = (info[UIImagePickerControllerOriginalImage] as? UIImage){
imagesArray = [pickedimage,pickedimage,pickedimage]//Will store three selected images in your array
myCollectionView.reloadData()
}
dismiss(animated: true, completion: nil)
}
}
4 回答
在您的cellForItemAt方法中,只需将
as! cell
替换为Your_Cell_Class_Name
因为代码中没有名为cell的类 .Happy Coding
您必须在“属性”检查器中设置标识符 .
点击故事板中的整个单元格 .
选择属性检查器
提供标识符名称(例如标识符=单元格)
有关更多说明 - 第一张图片
第二张图片
如果您以编程方式创建自定义集合ViewCell而不是使用StoryBoards,则以下步骤将对您有所帮助 .
然后在
cellForItemAt
方法中投射自定义单元格从错误消息中很清楚:
正如其他人所说,
as! cell
是错误的 . 运算符as!
表示 Type casting ,因此在as
之后必须输入类型名称或类名称而不是变量 .See Swift Official Guide