以编程方式创建UICollectionView

时间:2016-11-10 14:47:24

标签: ios swift uicollectionview uicollectionviewdelegate

我正在学习如何以编程方式创建UICollectionView。我想在应用程序的另一部分创建从用户收集的图片网格。 这个示例代码能帮助我实现这个目标吗?另外,如何配置数据以发出我想要的图像?我的源代码如下。

UICollectionView:

class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageStore = ImageStore()
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 100, height: 100)

        let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        myCollectionView.dataSource = self
        myCollectionView.delegate = self
        myCollectionView.registerClass(RDCellCollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(myCollectionView)
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    var images: [UIImage] = [

    ]

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! RDCellCollectionViewCell
        myCell.imageView.image = images[indexPath.item]
        myCell.backgroundColor = UIColor.grayColor()
        return myCell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        print("User tapped on item \(indexPath.row)")
    }
}

ImageStore.swift:

class ImageStore: NSObject {

    let cache = NSCache()

    func setImage(image: UIImage, forKey key: String) {
        cache.setObject(image, forKey: key)

        let imageURL = imageURLForKey(key)

        if let data = UIImageJPEGRepresentation(image, 0.5) {
            data.writeToURL(imageURL, atomically: true)
        }
    }
    func imageForKey(key: String) -> UIImage? {
        if let existingImage = cache.objectForKey(key) as? UIImage {
            return existingImage
        }

        let imageURL = imageURLForKey(key)
        guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
            return nil
        }

        cache.setObject(imageFromDisk, forKey: key)
        return imageFromDisk
    }

    func deleteImageForKey(key: String) {
        cache.removeObjectForKey(key)

        let imageURL = imageURLForKey(key)
        do {
            try NSFileManager.defaultManager().removeItemAtURL(imageURL)
        }
        catch let deleteError {
            print("Error removing the image from disk: \(deleteError)")
        }
    }

    func imageURLForKey(key: String) -> NSURL {
        let documentsDirectories =
        NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let documentDirectory = documentsDirectories.first!

        return documentDirectory.URLByAppendingPathComponent(key)
    }
}

2 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。您需要创建一个包含UIImageView的UICollectionViewCell的子类;这将允许您在cellForItemAtIndexPath中将正确的UIImage插入其中。

这描述了如何连接自定义单元格: Create UICollectionViewCell programmatically without nib or storyboard

至于获取正确的图像,您需要以某种方式将索引路径映射到图像存储,以便项目编号对应于正确的图像密钥。

答案 1 :(得分:0)

如果任务是添加图像,你应该在cellForItemAtIndexPath中使用这样的东西:

let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath)
myCell.backgroundColor = UIColor.blueColor()
let imageView = UIImageView(frame: cell.contentView.frame)
cell.contentView.addSubview(imageView)
imageView.image = //Here you should get right UIImage like ImageStore().imageForKey("YOUR_KEY")
return myCell

或者您可以使用自定义UICollectionViewCell子类,如Joshua Kaden所写。