2016-01-31 128 views
2
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as UICollectionViewCell 
    var template: UIView 
    template = UIView.init(frame: CGRectMake(10, 10, 50, 50)) 
    template.backgroundColor = UIColor.redColor() 
    self.cell.addSubview(template) 

    return cell 
} 

在UICollectionView细胞添加的UIView编程我试图拖动的UIView插入故事板和addSubview到出口的CollectionView细胞,但它也不会工作。如何迅速

回答

1

self.cell中的“self”意味着它引用了一个类/全局变量,而不是您在该方法顶部创建的单元格。尝试更改self.cell.addSubview(template)cell.addSubview(template)

另外

var template: UIView 
template = UIView.init(frame: CGRectMake(10, 10, 50, 50)) 

可以被简化为:

let template = UIView(frame: CGRectMake(10, 10, 50, 50))