您的位置:首页 > 移动开发 > Swift

Swift自定义UICollectionViewCell不显示的解决方案

2015-01-20 15:40 495 查看
今天遇到一个问题,用Swift自定义UICollectionViewCell,按照之前用OC的路子会出现cell不现实的问题。具体原因也不知道,可能是个Swift的bug吧,具体解决方法是用代码添加cell的子视图。而且这里注意,是在cell的contentView上添加子视图,这样就能显示出来了。

以下是我写的一个继承UICollectionViewCell的子类

import UIKit

class CollectionViewCell: UICollectionViewCell {
var imageView: UIImageView!

var textLabel: UILabel!

override init(frame: CGRect) {
super.init(frame: frame)
self.imageView = UIImageView(frame: CGRectMake(15, 10, 125, 120))
self.textLabel = UILabel(frame:  CGRectMake(10, 135, 130, 21))
self.contentView.addSubview(self.imageView)
self.contentView.addSubview(self.textLabel)
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//self.imageView.
//fatalError("init(coder:) has not been implemented")
}
}
下面是代理方法

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CollectionViewCell

cell.textLabel?.text = "fsdfsafafsaf"
cell.imageView?.backgroundColor = UIColor.redColor()
return cell
}


而在nib中就什么也不要在拖拽子视图了,直接将cell 的clas修改为前面的CollectionViewCell就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: