UICollectionView's cell registerClass in Swift

前端 未结 4 693
既然无缘
既然无缘 2020-12-15 02:09

Right now I\'m using NSClassFromString, but is there a better way to get an AnyClass! from a class in Swift? I am trying to pass the reference to m

相关标签:
4条回答
  • 2020-12-15 02:54

    NSClassFromString("MyCoolViewCell")might get nil.
    Should add module name in prefix:
    collectionView.registerClass(NSClassFromString("MyApp.MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")

    If cellClass not a variable, use MyCoolViewCell.self is a better choice.

    0 讨论(0)
  • 2020-12-15 02:57

    In case you are using a nib file, use this code instead:

        let nib = UINib(nibName: "MyCoolViewCell", bundle: nil)
        collectionView?.register(nib, forCellWithReuseIdentifier: "MyCoolViewCellIdentifier")
    
    0 讨论(0)
  • 2020-12-15 03:03

    In Swift 3:

    self.collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "CustomCollectionViewCellReuseIdentifier")
    
    0 讨论(0)
  • 2020-12-15 03:06

    This is currently just a blind but educated guess, but using Class.self might be what you want.

    collectionView.registerClass(MyCoolViewCell.self, forCellWithReuseIdentifier: "MyCoolViewCell")
    
    0 讨论(0)
提交回复
热议问题