使用collectionview

时间:2018-01-31 12:43:37

标签: ios swift uicollectionview uicollectionviewcell xib

我有FeedCell.swift和FeedCell.xib,在feedcell xib我将单元格自定义类设置为' FeedCell'

视图控制器viewDidLoad中的代码

collectionView.register(UINib(nibName: "FeedCell", bundle: .main), forCellWithReuseIdentifier: "feedCell")

问题

我想继承FeedCell并将该类与collectionView一起使用 像:

class FeedCell:UICollectionViewCell {
    @IBOutlet weak var showImageView: UIImageView!
    @IBOutlet weak var showIconImageView: UIImageView!

}

class AppFeedCell: FeedCell { 
    override func awakeFromNib() {
       super.awakeFromNib()
       // configure cell
    }
}

如何使用collectionview注册/使用FeedCell和AppFeedCell?

4 个答案:

答案 0 :(得分:2)

如果您的 AppFeedCell 具有不同的UI配置,例如它不绑定在 FeedCell 中定义的某些IBOutlet,或者它添加了不在其超类中的新的IBOutlet,那么您将必须注册两个Nib(假设您有两个单独的Nib文件)

collectionView.register(UINib(nibName: "FeedCell", bundle: .main), forCellWithReuseIdentifier: "feedCell")
collectionView.register(UINib(nibName: "AppFeedCell", bundle: .main), forCellWithReuseIdentifier: "appFeedCell")

然后你可以在需要的时候将每个人出列。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:  NSIndexPath) -> UICollectionViewCell {
    if you_need_AppFeedCell {
        let cell : AppFeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("appFeedCell", forIndexPath: indexPath) as! AppFeedCell
        return cell
    } else
        let cell : FeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! FeedCell
        return cell
    }
}

这样,即使 AppFeedCell 子类 FeedCell ,您也可能有两个不同的Nib文件。

否则,如果类和子类共享相同的单元格布局和插座,那么只需将出列的单元格( FeedCell )强制转换为 AppFeedCell 就足够了,无需注册另一个笔尖,如上面提到的 Taras Chernyshenko

答案 1 :(得分:1)

您无需为AppFeedCell注册单独的xib。您已将nib注册到collectionView。

将单元格出列并将其转换为cellForItemAtIndexPath中所需的类。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath 
    indexPath:  NSIndexPath) -> UICollectionViewCell {
if you_need_AppFeedCell {
    let cell : AppFeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! AppFeedCell
    return cell
} else
    let cell : FeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! FeedCell
    return cell
}
}

您的AppFeedCell将继承FeedCell的所有商店,因此它也可以正常运作。

答案 2 :(得分:0)

在您的单元格xib / storyboard中,转到身份检查器设置类:AppFeedCell

现在,在collectview的数据源方法中,您可以创建AppFeedCell类型的单元格。

答案 3 :(得分:0)

试试这个。

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

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

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell : AppFeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) as! AppFeedCell


    return cell
}
相关问题