在惰性初始化swift中访问继承的对象



只是想知道为什么在延迟初始化时无法访问继承的对象集合视图:

class FunCollectionLayout : UICollectionViewFlowLayout {
    var middleSection:Int = {
        let sectionCount = self.collectionView!.numberOfSections()
        return sectionCount/2
    }()
    func testFunc() {
        print((self.collectionView?.numberOfSections())! / 2)
    }
}

错误为:

Value of type 'NSObject -> () -> FunCollectionLayout' has no member 'collectionView'

您只是缺少lazy声明属性。

  lazy var middleSection:Int = {
    let sectionCount = self.collectionView!.numberOfSections()
    return sectionCount/2
  }()

但是,您没有将其作为计算属性,从而错过了要点。

  var middleSection: Int {
    let sectionCount = self.collectionView!.numberOfSections()
    return sectionCount / 2
  }

保持它的动态性,使它和collectionView保持同步,使它成为一个计算属性。

最新更新