Swift:实现没有集合视图控制器的集合视图

时间:2015-03-19 17:51:46

标签: ios swift uicollectionview

我设置了一个CollectionView 控制器,让事情很顺利,直截了当。

class CollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    .
    .
    .
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CollectionViewCell
        cell.myTitle.text = self.titles[indexPath.row]
        let imgName = "pic\(indexPath.row).jpg"
        cell.myImage.image = UIImage(named: imgName)

        return cell
    }
}
class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var myTitle: UILabel!
    @IBOutlet weak var myImage: UIImageView!
}

现在我只想使用UICollectionView UICollectionViewController)。我实现了我的集合,但是当我运行我的应用程序时,没有正在渲染的单元格。

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
class CollectionView: UICollectionView, UICollectionViewDelegateFlowLayout {
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CollectionViewCell
        cell.myTitle.text = self.titles[indexPath.row]
        let imgName = "pic\(indexPath.row).jpg"
        cell.myImage.image = UIImage(named: imgName)

        return cell
    }
}
class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var myTitle: UILabel!
    @IBOutlet weak var myImage: UIImageView!
}

我是否需要在ViewController中实施一些初始化?我假设我在这里遗漏了一些小事:(

*我正在使用Storyboard,因此我的Cell等在那里生成,而不是通过代码生成。

2 个答案:

答案 0 :(得分:4)

您的视图控制器是否设置为集合视图的委托和数据源?

您可以通过在视图控制器和集合视图之间进行控制拖动,从collectionView.delegate = self等代码或故事板中执行此操作。

答案 1 :(得分:0)

你应该点击这个链接: http://adoptioncurve.net/archives/2012/09/a-simple-uicollectionview-tutorial/ 想法是你需要注册nib(如果使用xib用于自定义单元格)或注册类自定义单元格和cellidentifier

相关问题