簡體   English   中英

在Swift collectionView中僅調用一次cellForItemAt

[英]cellForItemAt called only once in Swift collectionView

如果我將流布局與collectionView一起使用,則所有單元格都可以在數據中看到。 如果使用自定義布局,則僅對索引(0,0)訪問cellForItemAt,並且相應地僅顯示單個單元格。

我很困惑為什么-請幫助!

下面的最小示例:

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
}

}

自定義單元

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
}}

自定義布局如果不在此處-我可以看到所有期望的單元格(盡管沒有我的首選布局)。 使用此功能時,我只會看到一個單元格。

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
    }}

輸出量

我想要所有七個小矮人!

問題在於contentSize值

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

只需將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)
    }

而且您將看到多個單元格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM