2017-02-12 45 views
0

我是編碼的初學者,我想學習設計iOS移動應用。我通過重新創建通過觀看Youtube而建立的應用程序來學習。我正在重新創建Facebook新聞提要。以下是我學到的自定義代碼。我被困在構建單元格的部分和它們的大小上。具體來說,我收到了以下錯誤:collectionView?.registerClass(FeedCell.self,forCellWithReuseIdentifier:cellId)。這似乎是以前的Swift版本中可行的聲明,但不是3.0。謝謝你的幫助!UICollectionView在移動應用上創建新聞源的代碼

下面是代碼:

import UIKit 

let cellId = "cellId" 

class FeedController: UICollectionViewController, UICollectionViewDelegateFlowLayout { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    navigationItem.title = "Facebook Feed" 


    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1) 

    collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: cellId) 


} 

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return 3 
} 
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) 
} 

func collectionView(_collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    return CGSize(width: view.frame.width, height: 50) 



} 
} 

class FeedCell: UICollectionViewCell { 

    override init(frame: CGRect){ 
     super.init(frame: frame) 

     setupViews() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func setupViews() { 

    backgroundColor = UIColor.white 

回答

5

當你創建一個自定義的CollectionView電池必須使用「collectionView.registerNib」,而不是collectionView.registerClass。

collectionView.registerNib(UINib(nibName: "Your Nib Name", bundle: nil), forCellWithReuseIdentifier: "Your Cell Identifier") 
+0

你能否加上樣本代碼 – vshall

0

增加小區右鍵點擊任何地方,你要添加的文件:

enter image description here

選擇可可觸摸類

enter image description here

選擇類名和檢查還創造未來再XIB文件

enter image description here

終於

嘗試更換這行:

collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: cellId) 

collectionView?.register(UINib(nibName: "fileName", bundle: nil), forCellWithReuseIdentifier: cellId) 

「文件名」是您的xib文件名。

+0

謝謝你的上述幫助!我把代碼放到了AppDelegate.swift部分: –

+0

它是AppDelegate類:UIResponder,UIApplicationDelegate { –

+0

紅色的是,它聲明「線程1:信號SIGABRT」 –