2016-01-29 91 views
1

我有一个UICollectionView该自定义包含UICollectionViewCell的,这里是有关的代码: UICollectionView定制单元不显示

class customCell: UICollectionViewCell{ 
    var imgView = UIImageView() 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
     commonInit() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     commonInit() 
    } 
    func commonInit(){ 
     imgView.translatesAutoresizingMaskIntoConstraints = false 
     self.addcontentView.addSubview(imgView) 
     //add constraints 
    } 
} 


class CollectionViewController: UICollectionViewController { 
    private let imageLib = [...] //image file name strings 

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
     let cell : IconCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(keyIconCellReuse , forIndexPath: indexPath) as! IconCollectionViewCell 

     let image1 = (UIImage(named: imageLib[indexPath.row])?.imageWithRenderingMode(.AlwaysTemplate))! 
     cell.imgView = UIImageView(image: image1) 
     cell.imgView.tintColor = UIColor(white:0, alpha:0.7) 
     cell.userInteractionEnabled = true 

     return cell 

    } 

} 

这是它看起来像现在:

1o

+0

它似乎为每个加载的图像添加新的UIImageView。你能分享func setUp(imgString:String)方法体吗? –

回答

2

看起来像cell.setup(imageLib[indexPath.row])增加了一个新的UIImageView与新的图像,而不是重复使用剪切的代码部分中的现有人。

出于性能原因,请不要在collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)之内初始化任何视图。只需将相应的图像分配给属于该单元的图像视图。

请注意,单元格会被集合视图重复使用。

编辑

与更新的问题,你在做

let image1 = (UIImage(named: imageLib[indexPath.row])?.imageWithRenderingMode(.AlwaysTemplate))! 
    cell.imgView = UIImageView(image: image1) 
    cell.imgView.tintColor = UIColor(white:0, alpha:0.7) 
    cell.userInteractionEnabled = true 

只是

let image1 = (UIImage(named: imageLib[indexPath.row])?.imageWithRenderingMode(.AlwaysTemplate))! 
cell.imgView.image = image1 

commonInit()做尽可能多的其他设置成为可能。

+0

但如果我想要一个单元格数组加载一个图像数组,应该怎么做 - 我应该把所有东西放在自定义单元格中的初始化代码中吗? – Liumx31

+0

让集合视图做它的工作,并选择放置哪个单元格,只需根据'indexPath'设置图像。 – SmokeDispenser

+0

我刚刚更新了我的代码,但似乎遇到了另一个问题,您能否看看? – Liumx31

相关问题