2014-11-06 17 views
6

Có giải pháp cho vấn đề này không?Swift 'không có thành viên có tên'

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

xcode mang lại cho tôi những lỗi sau

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

tôi có thể làm cho nó trở thành một tùy chọn và khởi nó trong phương thức init, nhưng tôi đang tìm một cách để làm cho collectionview một let và không a var

Trả lời

3

Bạn có thể gán giá trị ban đầu cho biến thành viên không đổi trong trình khởi tạo của mình. Không cần phải làm cho nó là var hoặc tùy chọn.

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") 
    } 
} 
0

Tại thời điểm đó không có collectionFlowLayout được tạo để nó phàn nàn rằng không có thành viên nào có tên như vậy.

Các giải pháp có thể được như bạn đề cập đến để làm cho nó không bắt buộc và khởi nó trong init hoặc bạn có thể làm điều này:

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

@MehulThakkar Tôi đã thử cade của bạn trong xCode 6.1 và nó không hoạt động. – Greg

1

Thiết hãy biến (hằng số) trong phương thức init:

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

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

Chúng ta có thể truy cập các biến cho phép với chính mình.

Hy vọng rằng nó phù hợp với bạn.

Các vấn đề liên quan