【问题标题】:Swift 'does not have a member named'斯威夫特“没有一个名为”的成员
【发布时间】:2015-01-02 17:55:19
【问题描述】:

这个问题有解决办法吗?

class ViewController : UIViewController {
    let collectionFlowLayout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: collectionFlowLayout)
}

xcode 给我以下错误

ViewController.swift: 'ViewController.Type' does not have a member named 'collectionFlowLayout'

我可以将其设为可选并在 init 方法中对其进行初始化,但我正在寻找一种方法使 collectionview 成为 let 而不是 var

【问题讨论】:

    标签: ios xcode swift var let


    【解决方案1】:

    您可以在初始化程序中为常量成员变量分配初始值。无需将其设为 var 或可选。

    class ViewController : UIViewController {
        let collectionFlowLayout = UICollectionViewFlowLayout()
        let collectionView : UICollectionView
    
        override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
        {
            self.collectionView = UICollectionView(frame: CGRectZero, 
                                    collectionViewLayout: self.collectionFlowLayout);
    
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
        }
    
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    【讨论】:

      【解决方案2】:

      在init方法中设置let变量(常量):

      class ViewController : UIViewController {
          let collectionFlowLayout: UICollectionViewFlowLayout!
          let collectionView: UICollectionView! 
      
          init() {
              super.init()
              self.collectionFlowLayout = UICollectionViewFlowLayout()
              self.collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: collectionFlowLayout)
          }
      }
      

      我们可以用 self 访问 let 变量。

      希望它对你有用。

      【讨论】:

        【解决方案3】:

        那时没有创建collectionFlowLayout,所以它抱怨没有这样命名的成员。

        解决方案可以像您提到的那样使其成为可选并在 init 中对其进行初始化,或者您可以这样做:

        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        

        【讨论】:

        • @MehulThakkar 我在 xCode 6.1 中尝试了你的 cade,但它不起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多