nicklockwood / layout

A declarative UI framework for iOS
MIT License
2.23k stars 97 forks source link

Create custom UICollectionViewCell #153

Closed vegidio closed 5 years ago

vegidio commented 5 years ago

I'm trying to create a custom UICollectionViewCell, but I'm having some problems. Here is what I'm doing:

  1. I created a cell layout called MyCustomCell.xml:
<UICollectionViewCell>

    <UILabel
        outlet="labelName"
        text="Name" />

</UICollectionViewCell>
  1. I created a custom UICollectionViewCell called MyCustomCollectionViewCell.swift that reads the layout above:
import Layout
import UIKit

class MyCustomCollectionViewCell: UICollectionViewCell, LayoutLoading
{
    @IBOutlet private weak var labelName: UILabel?
    var layoutNode: LayoutNode?

    override init(frame: CGRect) {
        super.init(frame: frame)
        loadLayout(named: "MyCustomCell.xml")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // Ensure layout is updated after screen rotation, etc
        self.layoutNode?.view.frame = self.bounds

        // Update frame to match layout
        self.frame.size = self.intrinsicContentSize
    }

    public override var intrinsicContentSize: CGSize {
        return layoutNode?.frame.size ?? .zero
    }
}

Then I tried to use this custom cell in my UICollectionView. My collection view also uses Layout and it's created like this:

  1. This is the layout file:
<UICollectionView
    outlet="collectionView"
    backgroundColor="#ffffff">

    <MyCustomCollectionViewCell reuseIdentifier="cell" />

</UICollectionView>
  1. And this the class that loads the layout above:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellNode(withIdentifier: "cell", for: indexPath)
    return cell as! MyCustomCollectionViewCell
}

But after I do all this, I get the error message UICollectionViewCells must be created by UICollectionView in MyCustomCollectionViewCell.xml

My idea is to reuse MyCustomCollectionViewCell in different UICollectionViews so, how can I prevent the error above?

Thanks.

vegidio commented 5 years ago

Sorry, I created a duplicated ticket. I'm closing this one