在Collectionview中如何根据选择设置颜色

在Collectionview中如何根据选择设置颜色

本文介绍了在Collectionview中如何根据选择设置颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是默认颜色设置 indexPath ,我想根据选择更改颜色。

My requirement is to set by default color at first indexPath and I want to change colors according to selection.

我的要求是当collectionview将加载在第一个索引背景颜色应该是红色。和取消选择的颜色是蓝色。
如何管理这个
这是我的代码

My Requirement is when collectionview will load at first index background color should be Red Color.and deselected color is blue color.how to manage thisHere is my code

import UIKit
class MyCollectionViewCell: UICollectionViewCell {
override var selected: Bool {
    didSet {
        contentView.backgroundColor = selected ? UIColor.redColor(): UIColor.blueColor()
    }
}
}

class ViewController: UIViewController {
@IBOutlet var collView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

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

// make a cell for each cell index path
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCollectionViewCell", forIndexPath: indexPath) as! MyCollectionViewCell
    if(indexPath.row == 0) { //for first cell in the collection
        cell.backgroundColor = UIColor.redColor()
    } else {
        cell.backgroundColor = UIColor.blueColor()
    }

    return cell
}

}

我的输出是

问题是当我点击第一个 indexPath 它工作,但通过选择其他我的两种颜色是相同的

Issue is when I click on first indexPath it works but by selecting others my two colors are same

推荐答案

viewDidLoad 中重新载入 collectionView 以这种方式显式选择第一个单元格。

In your viewDidLoad reload the collectionView and after that explicitly select the first cell like this way.

collView.reloadData()
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
collView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .None)


$ b b

注意:现在,您不需要在 cellForIteamAtIndexPath 中添加颜色更改代码,即可删除该代码。

Note : Now there is no need to add code of color changing inside your cellForIteamAtIndexPath remove that code.

这篇关于在Collectionview中如何根据选择设置颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:44