Inline property instantiation not working for generic UICollectionViewCell subclasses

蓝咒 提交于 2019-12-11 04:12:46

问题


If I define a UICollectionViewCell subclass:

class TestCell<T>: UICollectionViewCell {
  var float: CGFloat? = 3
  var string = "abc"
}

Register it:

collectionView.registerClass(TestCell<String>.self, forCellWithReuseIdentifier: "Test")

Then use it:

collectionView.dequeueReusableCellWithReuseIdentifier("Test", forIndexPath: indexPath) as! TestCell<String>

I notice strange behavior with the properties that should have been initialized.

  • float == Optional(0.0)
  • string == ""

Why is this happening and how can I fix it?

This is on Xcode 7.3


回答1:


Looks like this was a bug related to generics.

If you get rid of the generic specifier, the variables are initialized as you expect.

If you need the generic specifier, you can workaround the issue by instantiating the properties in the init method rather than inline:

class TestCell<T>: UICollectionViewCell {
  override init(frame: CGRect) {
    float = 3
    string = "abc"
    super.init(frame: frame)
  }

  var float: CGFloat?
  var string: String
}


来源:https://stackoverflow.com/questions/38194153/inline-property-instantiation-not-working-for-generic-uicollectionviewcell-subcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!