xcode Swift'没有名为'的成员'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26775865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:06:47  来源:igfitidea点击:

Swift 'does not have a member named'

iosxcodeswiftvarlet

提问by Andy Jacobs

Is there a solution for this problem ?

这个问题有解决方案吗?

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

xcode gives me the following error

xcode 给了我以下错误

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

i could make it an optional and initialise it in the init method, but i'm looking for a way to make the collectionview a let and not a var

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

采纳答案by Darren

You can assign initial values to constant member variables in your initializer. There's no need to make it a varor optional.

您可以在初始化程序中为常量成员变量分配初始值。没有必要让它成为一个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")
    }
}

回答by billyklh

Setting let variables(constants) in the init method:

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

class ViewController : UIViewController {
    let collectionFlowLayout: UICollectionViewFlowLayout!
    let collectionView: UICollectionView! 

    init() {
        super.init()
        self.collectionFlowLayout = UICollectionViewFlowLayout()
        self.collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: collectionFlowLayout)
    }
}

We can access the let variables with self.

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

Hope that it works for you.

希望它对你有用。

回答by Greg

At that point there is not collectionFlowLayoutcreated so it complains that there is no member named like that.

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

The solution can be as you mentioned to make it optional and initialise it in init or you can do this:

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

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