Swift中不存在名为“xxxx”的成员。

6
这个问题有解决方案吗?
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方法中进行初始化,但我正在寻找一种使集合视图成为let而不是var的方法。
3个回答

3

您可以在初始化器中为常量成员变量分配初始值。不需要将其设置为 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")
    }
}

1
在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变量。
希望这对你有用。

0

此时还没有创建collectionFlowLayout,因此它会抱怨找不到这个成员。

解决方案可以像您提到的那样将其设置为可选项并在init中初始化,或者您可以这样做:

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

@MehulThakkar 我在xCode 6.1中尝试了你的代码,但它无法工作。 - Greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接