简体   繁体   English

如何在UICollectionView Swift中显示多个图像

[英]How to show multiple images in UICollectionView Swift

This extension gives only one UIImageView inside CollectionView. 此扩展仅在CollectionView中提供一个UIImageView。 How to show more images, depends of the size of photos array. 如何显示更多图像,取决于照片阵列的大小。 Photos array contains array of Url to images (String). Photos数组包含用于图像的Url数组(字符串)。

extension FlatViewController: UICollectionViewDataSource{
        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return (flat.photos?.count)!
        }
        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CustomCollectionViewCell

            cell.imageView.loadImageFromURL(NSURL(string: flat.image!)!)
            return cell
        }
    }

Well you can simply go into Interface Builder and put in the amount of ImageView elements into your CollectionViewCell as you would want. 好了,您可以简单地进入Interface Builder,然后将所需的ImageView elements放入CollectionViewCell中。 Then create IBOutlets to reference your added ImageView elements in your CollectionViewController . 然后创建IBOutlets来引用CollectionViewController添加的ImageView元素。 Then within the function cellForItemAtIndexPath just plug in each the Image URL for each IBOutlet ImageView's . 然后在cellForItemAtIndexPath函数中,仅插入每个IBOutlet ImageView's每个Image URL。

That should work. 那应该工作。

In UICollectionViewCell subclass programmatically create UIImageView s based on the photos array's subarrays. UICollectionViewCell子类中,可以基于photos数组的子数组以编程方式创建UIImageView You can do this by setting up two protocols and implementing a delegate pattern where your FlatViewController is the delegate of your subclass. 您可以通过设置两个协议并实现一个委托模式(其中FlatViewController是子类的委托)来实现此目的。

The protocols would look something like this: 协议看起来像这样:

protocol PhotoDelegate {

  var photos: [[NSURL]] { get set }

}

protocol HasPhotos {

  var delegate: PhotoDelegate! { get set }

}

The delegate pattern will allow you to access the photos array from the subclass. 委托模式将允许您从子类访问photos数组。 You should set the dequeued cell variable's delegate property and cast it as your subclass in cellForRowAtIndexPath . 您应该设置出队单元格变量的委托属性,并将其cellForRowAtIndexPathcellForRowAtIndexPath的子类。 Like So 像这样

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "<Insert Identifier>", for: indexPath) as! Subclass
cell.delegate = self

If you have any questions just ask! 如果你有问题,就问吧! I love to help. 我很乐意提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM