in Collectionview how to set colors according to selection?
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)
Note : Now there is no need to add code of color changing inside your cellForIteamAtIndexPath
remove that code.
Set selected color of cell in UiCollectionView in swift
For two different colors based on selected state of the cell, you may need to subclass your UICollectionViewCell like this:
import UIKit
class YourCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView! // for example - some UI element inside cell ...
override var isSelected: Bool {
didSet {
self.contentView.backgroundColor = isSelected ? UIColor.blue : UIColor.yellow
self.imageView.alpha = isSelected ? 0.75 : 1.0
}
}
}
// and below you will have your original code
class YourViewController: UICollectionViewController {
... etc
Answering your question - for exceptional style of the first cell:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell ...
if(indexPath.row == 0) { //for first cell in the collection
cell.backgroundColor = UIColor.orange
} else {
cell.backgroundColor = UIColor.green
}
How to change Color of cell in UiCollectionView if just two can be selected
I'd do it this way:
- Use custom UICollectionViewCell subclass (without button because collection view cell handles selection itself)
in this cell class override
isSelected
property like this:override var isSelected: Bool {
didSet {
// set color according to state
self.backgroundColor = self.isSelected ? .blue : .clear
}
}In class which controls your
collectionView
performcollectionView.allowsMultipleSelection = true
In your
UICollectionViewDelegate
implement method (which will prevent selection of more than two cells at a time):func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return (collectionView.indexPathsForSelectedItems?.count ?? 0) < 2
}
This way you don't need a button inside the cell.
how to change cell background colour on selected item in UICollectionView and change other Cell colour to default in swift
Create a variable inside the vc
var currentSelected:Int?
then inside cellForItemAt
cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
finally didSelectItemAt
currentSelected = indexPath.row
collectionView.reloadData()
Don't depend on
isSelected
as cells are dequeued and when you scroll you'll get unexpected results
IOS Swift CollectionView How can I set the correct background color on index
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoriesCVC", for: indexPath) as! CategoriesCVC
cell.items.tag = indexPath.row
cell.items.setTitle(categoryTypes[indexPath.row], for: .normal)
if categoryTypes[indexPath.row] == "All" && indexPath.row == CategoryIndex {
cell.items.backgroundColor = UIColor(hexString: BlueBackground)
cell.items.setTitleColor(.white, for: .normal)
} else {
// set your normal cell color here
cell.items.backgroundColor = UIColor(hexString: NormalCellColor)
cell.items.setTitleColor(.normalTitleColoe, for: .normal)
}
return cell
}
Since collection view uses the dequeued cell, it takes the old cell background. that is blue color. if you revert the cell color in the else block, that will fix your issues
if you want to do in more Professional way. on cell prepareForReuse
, do your cleanups.
override open func prepareForReuse() {
super.prepareForReuse()
// Set your default background color, title color etc
}
Change label color when collectionView Cell is selected in Swift iOS
First, you should not be adding subviews in cellForItemAt
... cells are reused, and you end up adding the subviews multiple times in each cell.
Instead, add your subviews in your cell class when it is instantiated.
Then, add this to your cell class:
override var isSelected: Bool {
didSet {
label.textColor = isSelected ? .white : .black
}
}
No need to do anything in your controller on didSelectItemAt
or didDeselectItemAt
Edit -- here is a very simple example...
The cell class:
class MyCardCell: UICollectionViewCell {
let label: UILabel = {
let v = UILabel()
return v
}()
let cardView: UIView = {
let v = UIView()
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
cardView.backgroundColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
cardView.layer.cornerRadius = 8
cardView.layer.shadowOffset = CGSize(width: 0.2, height: 0.2)
cardView.layer.shadowRadius = 1
cardView.layer.shadowOpacity = 0.4
cardView.layer.borderColor = CGColor(red:0.00, green:0.00, blue:0.00, alpha:0.2)
cardView.layer.borderWidth = 0.4
cardView.clipsToBounds = true
label.textAlignment = .center
label.textColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.8)
label.font = UIFont.systemFont(ofSize: 9, weight: .semibold)
[cardView, label].forEach { v in
v.translatesAutoresizingMaskIntoConstraints = false
}
cardView.addSubview(label)
contentView.addSubview(cardView)
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
cardView.topAnchor.constraint(equalTo: g.topAnchor),
cardView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
cardView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
cardView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
label.centerYAnchor.constraint(equalTo: cardView.centerYAnchor),
label.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 12.0),
label.trailingAnchor.constraint(equalTo: cardView.trailingAnchor, constant: -12.0),
])
}
override var isSelected: Bool {
didSet {
label.textColor = isSelected ? .white : .black
// see the difference between setting
// cardView.backgroundColor
// or
// contentView.backgroundColor
cardView.backgroundColor = isSelected ? UIColor(red: 0.99, green: 0.71, blue: 0.25, alpha: 1.00) : UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
//contentView.backgroundColor = isSelected ? UIColor(red: 0.99, green: 0.71, blue: 0.25, alpha: 1.00) : UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
}
}
}
and a sample view controller class:
class TestCardCollectionVC: UIViewController {
var collectionView: UICollectionView!
var type: [String] = ["All","Coffee Shops","Pizza Places","Restaurants","Desserts"]
override func viewDidLoad() {
super.viewDidLoad()
let fl = UICollectionViewFlowLayout()
fl.scrollDirection = .horizontal
fl.minimumLineSpacing = 0
fl.minimumInteritemSpacing = 0
fl.estimatedItemSize = CGSize(width: 50, height: 40)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: g.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
collectionView.heightAnchor.constraint(equalToConstant: 40.0)
])
collectionView.backgroundColor = .systemBackground
collectionView.register(MyCardCell.self, forCellWithReuseIdentifier: "cardCell")
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension TestCardCollectionVC: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return type.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: "cardCell", for: indexPath) as! MyCardCell
c.label.text = type[indexPath.item]
return c
}
}
The output on launch (no cell selected):
selecting the 3rd cell:
selecting the 4th cell:
How to change the background color of a custom Collection View cell in swift iOS?
You can use selectedBackgroundView
property of UICollectionViewCell
for that, inside cellForItemAt indexPath
set that property and now when you select cell it will automatically change the backgroundColor
of that cell.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//Your other code
//Add code to set selectedBackgroundView property
let view = UIView(frame: cell.bounds)
// Set background color that you want
view.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.selectedBackgroundView = view
return cell
}
Using this now there is no need to change backgroundColor
of cell in didSelectItemAt indexPath
it will work automatically and change backgroundColor
for that selected cell.
How change color of a selected item?
In the document, there is a section shows you how to change color of a selected item.
CollectionView has a Selected VisualState that can be used to initiate a visual change to the selected item in the CollectionView:
In your case, change the backgroundColor
of stacklayout
would work:
<ContentPage.Resources>
<Style TargetType="StackLayout">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor"
Value="LightSkyBlue" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
</ContentPage.Resources>
<CollectionView SelectionMode="Single">
<CollectionView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Baboon</x:String>
<x:String>Capuchin Monkey</x:String>
<x:String>Blue Monkey</x:String>
<x:String>Squirrel Monkey</x:String>
<x:String>Golden Lion Tamarin</x:String>
<x:String>Howler Monkey</x:String>
<x:String>Japanese Macaque</x:String>
</x:Array>
</CollectionView.ItemsSource>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding .}" TextColor="Black"/>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Another way is binding the BackgroundColor with the property in your ViewModel and change it when the item is selected:
<Label Text="{Binding .}" TextColor="Black" BackgroundColor="{Binding backColor}"/>
Related Topics
Change Title of a Navigation Bar Button Item
Uitextfield Keyboard with Only Alphabet, No Numbers, No Caps, No Spacebar
How Parsing Firebase Fdatasnapshot JSON Data in Swift
Uitableview Inside Uitableviewcell with Dynamic Height
Geolocation by Iphone's Ip Address
Start/Stop Image View Rotation Animations
What Is Correct Way to Notify View Controller from Appdelegate
Differrence Between Closure and Function as Argument in Swift
How to Change the Font Size of a Uilabel in Swift
Receipt Validation on iOS In-App-Purchase Returns Multiple Transaction
Avaudiocompressedbuffer to Uint8 Array and Vice Versa
Restkit, Coredata and Swift - I Can't Seem to Fetch Results Back Out
Moya/Alamofire - Url Encoded Params with Same Keys
Sectioning Tableview and Rows with Core Data Swift