当我尝试使用自己的UICollectionViewCell类时,为什么会出现此错误?

问题描述 投票:1回答:1

我把UICollectionView放进了UIView

我正在使用自己的UICollectionViewCell课程。

3.错误是“类型'TimeLineViewController'不符合协议UICollectionViewDataSource

4.如果我将func collectionView(collectionView: UICollectionViewcellForItemAtIndexPath indexPath: NSIndexPath)的返回类型更改为UICollectionViewCell,则不会出现错误。

这是我的代码:

import UIKit

class TimeLineViewController: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate {

@IBOutlet weak var TimeLineColleciontView: UICollectionView!

// TODO TODO set cell size permeantly
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width-20,
        height: (collectionView.frame.width-20) * 1.2 )
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> TimeLineCollectionViewCell {
    let id = "TimeLineCell"
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(id, forIndexPath: indexPath) as! TimeLineCollectionViewCell
    return cell
}

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.TimeLineColleciontView.backgroundColor = UIColor(white: 0, alpha: 0)

    TimeLineColleciontView.dataSource = self
    TimeLineColleciontView.delegate = self

    // 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.
}


}

我的细胞类很简单:

import UIKit

class TimeLineCollectionViewCell: UICollectionViewCell {

var cover : UIImageView = UIImageView()
var date : UILabel = UILabel()

override func awakeFromNib() {
    cover.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)
    date.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    self.insertSubview(cover, atIndex: 0)
    self.insertSubview(date, atIndex: 2)
}
}
ios swift uicollectionview uicollectionviewcell
1个回答
1
投票

为了使TimeLineViewController类符合UICollectionViewDataSource协议,你应该为UICollectionViewCell函数返回cellForItemAtIndexPath。由于您已将函数签名(返回类型)更改为TimeLineCollectionViewCell,因此您收到此错误。

cellForItemAtIndexPath函数的返回类型设为UICollectionViewCell,并在函数中返回TimeLineCollectionViewCell的出列实例。由于UICollectionViewCellTimeLineCollectionViewCell的父类,因此您不会看到错误。

注意:您必须在必要时将返回的UICollectionViewCell值从cellForItemAtIndexPath转换为TimeLineCollectionViewCell

© www.soinside.com 2019 - 2024. All rights reserved.