2016-03-02 81 views
0

代码非常简单,但我不知道为什么它不起作用。我想要做的是将第5个单元格的颜色或第二列和第二个单元格的颜色更改为黑色,而不是白色。如何更改UICollectionView中特定单元格的颜色

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var x: UICollectionView! 

    var place = NSIndexPath(forItem: 1, inSection: 1) 

    @IBAction func y(sender: AnyObject) { 

     x.cellForItemAtIndexPath(place)?.backgroundColor = UIColor.blackColor() 

    } 

    @IBAction func z(sender: AnyObject) { 

     x.cellForItemAtIndexPath(place)?.backgroundColor = UIColor.whiteColor() 

    } 

} 

回答

1

如果要更改单元格的背景,那么它的,你必须在内容查看管理,例如:

cell.contentView.backgroundColor = UIColor.whiteColor() 

所以你的情况,你可以取代你的功能:

@IBAction func y(sender: AnyObject) { 

    self.x.cellForItemAtIndexPath(place)?.contentView.backgroundColor = UIColor.blackColor() 

} 

@IBAction func z(sender: AnyObject) { 

    self.x.cellForItemAtIndexPath(place)?.contentView.backgroundColor = UIColor.whiteColor() 

} 

此外,如果要更改第五单元背景颜色的indexPath应该是:

var place = NSIndexPath(forItem: 4, inSection: 0) 

我注意到你正在尝试做第1行和第1列,所以它的forItem:1和inSection:1,它不像IOS中那样工作。 UICollectionView包含项目和部分,collectionView中的项目从左边开始写入item0 item1 item2 ..等等,默认情况下它在第0部分中,例如,您添加另一个部分,其中第1部分将放入其他项目,这将是item0,项目2,项目3 ..等,但其在第1节等等,这里更多关于它:Apple Documentation

确保您设置数据源到你的ViewController:

class ViewController: UIViewController,UICollectionViewDataSource { 

     override func viewDidLoad() { 
     super.viewDidLoad() 

     x.dataSource = self 

    } 


    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { 

     return 1 
    } 


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

     return 20 
    } 

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

    // Configure the cell 


    return cell 
    } 
} 

它应该很好地工作,祝你好运 !

+0

谢谢,但它没有工作,仍然没有颜色变化... – PKLJ

+0

@PKLJ,检查我更新的答案! – AaoIi

+0

@Aaoli有一个错误:类型ViewController不符合协议'UIViewDataSource',并且我的CollectionView有三行三列,NSIndexPath仍然是(forItem:4,inSection:0)? – PKLJ