内联属性实例化不适用于通用UICollectionViewCell子类 [英] Inline property instantiation not working for generic UICollectionViewCell subclasses

查看:90
本文介绍了内联属性实例化不适用于通用UICollectionViewCell子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义了UICollectionViewCell子类:

If I define a UICollectionViewCell subclass:

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

注册:

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

然后使用它:

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

我注意到应该初始化的属性具有奇怪的行为.

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

  • float ==可选(0.0)
  • string =="

为什么会这样,我该如何解决?

Why is this happening and how can I fix it?

这是在Xcode 7.3上

This is on Xcode 7.3

推荐答案

看起来像是与泛型相关的错误.

Looks like this was a bug related to generics.

如果摆脱了通用说明符,变量将按预期进行初始化.

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

如果需要通用说明符,可以通过实例化init方法而不是内联方法的属性来解决此问题:

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
}

这篇关于内联属性实例化不适用于通用UICollectionViewCell子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆