简体   繁体   English

在Swift collectionView中仅调用一次cellForItemAt

[英]cellForItemAt called only once in Swift collectionView

If I use flow layout with collectionView, then all my cells are visible with the data. 如果我将流布局与collectionView一起使用,则所有单元格都可以在数据中看到。 If I use a custom layout, then cellForItemAt is only accessed for index (0,0), and correspondingly only a single cell is displayed. 如果使用自定义布局,则仅对索引(0,0)访问cellForItemAt,并且相应地仅显示单个单元格。

I'm baffled why - please help! 我很困惑为什么-请帮助!

Minimal example below: 下面的最小示例:

ViewController: ViewController:

import UIKit
private let reuseIdentifier = "customCell"

class customCollectionViewController: UICollectionViewController {

@IBOutlet var customCollectionView: UICollectionView!


let dwarfArray = ["dopey", "sneezy", "bashful", "grumpy", "doc", "happy", "sleepy"]


override func viewDidLoad() {
    super.viewDidLoad()
}

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}


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

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! customCollectionViewCell

    let cellContentsIndex = indexPath.row
    if cellContentsIndex <= dwarfArray.count
    {
        cell.displayContent(name: dwarfArray[cellContentsIndex])
    }

    return cell
}

} }

Custom Cell 自定义单元

import UIKit
class customCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!

required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    override init(frame: CGRect){
        super.init(frame: frame)
    }

    public func displayContent(name: String){
       nameLabel.text = name

    }

func setup(){
    self.layer.borderWidth = 1.0
    self.layer.borderColor = UIColor.black.cgColor
}}

Custom Layout If this is not here - I can see all the cells I expect (albeit without my preferred layout). 自定义布局如果不在此处-我可以看到所有期望的单元格(尽管没有我的首选布局)。 When I use this, I only see one cell. 使用此功能时,我只会看到一个单元格。

import UIKit
class customCollectionViewLayout: UICollectionViewLayout {
let CELL_SIZE = 100.0

    var cellAttrsDictionary = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()
    //define the size of the area the user can move around in within the collection view
    var contentSize = CGSize.zero

    var dataSourceDidUpdate = true

    func collectionViewContentSize() -> CGSize{
        return self.contentSize
    }

    override func prepare() {
        if (collectionView?.numberOfItems(inSection: 0))! > 0 {
            /// cycle through each item of the section
            for item in 0...(collectionView?.numberOfItems(inSection: 0))!-1{
                /// build the collection attributes
                let cellIndex = NSIndexPath(item: item, section: 0)
                let xPos = Double(item)*CELL_SIZE
                let yPos = 40.0

                let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: cellIndex as IndexPath)
                cellAttributes.frame = CGRect(x: xPos, y:yPos, width: CELL_SIZE, height: CELL_SIZE)
                // cellAttributes.frame = CGRect(x: xPos, y:yPos, width: CELL_WIDTH + 2*CELL_SPACING, height: CELL_HEIGHT)
                cellAttributes.zIndex = 1

                //save
                cellAttrsDictionary[cellIndex] = cellAttributes
            }
        }
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        /// create array to hold all the elements in our current view
        var attributesInRTect = [UICollectionViewLayoutAttributes]()

        /// check each element to see if they should be returned
        for cellAttributes in cellAttrsDictionary.values  {
            if rect.intersects(cellAttributes.frame)
            {
                attributesInRTect.append(cellAttributes)
            }
        }

        return attributesInRTect
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return cellAttrsDictionary[indexPath as NSIndexPath]!
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }}

Output 输出量

我想要所有七个小矮人!

The problem is with contentSize value 问题在于contentSize值

 func collectionViewContentSize() -> CGSize{
        return self.contentSize
 }

Just replace func collectionViewContentSize()... by something like this: 只需将func collectionViewContentSize()...替换为以下内容:

    func lastLayoutAttributes() -> UICollectionViewLayoutAttributes? {
        return cellAttrsDictionary.values.map { $0 }.sorted(by: { $0.frame.maxX < $1.frame.maxX }).last        
    }

    override var collectionViewContentSize: CGSize {
        guard let collectionView = collectionView else { return .zero }
        guard collectionView.frame != .zero else { return .zero }

        let width: CGFloat
        let height: CGFloat = collectionView.frame.height

        if let lastLayoutAttributes = lastLayoutAttributes() {
            width = lastLayoutAttributes.frame.maxX
        } else {
            width = 0
        }

        return CGSize(width: width, height: height)
    }

And you will see more than one cell. 而且您将看到多个单元格。

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

相关问题 CollectionView 方法 cellForItemAt indexPath:未被调用(Swift) - CollectionView method cellForItemAt indexPath: not being called (Swift) Swift DRY collectionView(_ cellForItemAt)调用 - Swift DRY collectionView(_ cellForItemAt) call 未调用UICollectionView方法(collectionView cellForItemAt indexPath) - UICollectionView method (collectionView cellForItemAt indexPath ) not called Swift 4 中的 UICollectionViewController 未调用 cellForItemAt 函数 - cellForItemAt function not getting called at UICollectionViewController in Swift 4 当我在 numberOfItemsInSection 中返回 1 时,在 Swift 中未调用 cellForItemAt - When I return 1 in numberOfItemsInSection cellForItemAt not called in Swift 集合视图 cellForItemAt indexPath 未被调用(Swift) - Collection view cellForItemAt indexPath not getting called (Swift) 在cellForItemAt集合视图中不通过Swift 3中的collectionView.reloadData()更新indexPath - In cellForItemAt collection view is not updating indexPath by collectionView.reloadData() in swift 3 cellForItemAt没有在collectionView中调用 - cellForItemAt is not calling in collectionView swift 函数只被调用一次 - swift function is only being called once GeoFire watchBlock在Swift项目中仅被调用一次 - GeoFire observeBlock are only called once in Swift project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM