I really don't know why my collectionViewCell disappear - swift

I making a calendar so first I make a array like this [0,0,0,0,1,2,3,4,...,31] by thing.optimize(month: 5). in this array, the reason I make 0 in front of 1,2,3,...,31 is
when I make cell, I'm using an if statement so if cell.text == 0 then I set cell.isHidden = true.
When I select the one cell I reload both of collectionView(collectionView,nextMonthCollectionView) and make round red shape.
When I select another button, a problem occurs,
suddenly the cell disappears. I added a photo of this.
First, this is my code.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nowMonthName: UILabel!
#IBOutlet weak var nextMonthName: UILabel!
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var nextMonthCollectionView: UICollectionView!
var thing = realOptimaize()
var selectedIndex : IndexPath?
var items = [UIBarButtonItem]()
var forCollectionViewCount : Int?
var monthData : Array<Int>?
var nextMonthData : Array<Int>?
override func viewDidLoad() {
monthData = thing.optimaize(month: 5)
nextMonthData = thing.optimaize(month: 6)
self.title = String(CalenderBrain.init().curruntYear)
nowMonthName.text = String(CalenderBrain.init().curruntMonthName())
nextMonthName.text = String(CalenderBrain.init().nextMonthName())
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.nextMonthCollectionView.dataSource = self
self.nextMonthCollectionView.delegate = self
self.collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier : "MyCell")
self.nextMonthCollectionView.register(UINib(nibName: "NextMonthCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MyCell2")
//이해가 잘 안가는 부분!!!
if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout{
layout.minimumInteritemSpacing = -0.2
}
if let layout2 = self.nextMonthCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
layout2.minimumInteritemSpacing = -0.2
}
}
}
`extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate,` UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.nextMonthCollectionView {
forCollectionViewCount = nextMonthData!.count
return forCollectionViewCount!
} else {
forCollectionViewCount = monthData!.count
return forCollectionViewCount!
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.nextMonthCollectionView{
let forCollectionViewCell = nextMonthCollectionView.dequeueReusableCell(withReuseIdentifier: "MyCell2", for: indexPath) as! NextMonthCollectionViewCell
// forCollectionViewCell.button.tag = indexPath.item
if nextMonthData![indexPath.row] == 0 {
forCollectionViewCell.isHidden = true
} else {
forCollectionViewCell.Label.text = String(nextMonthData![indexPath.row])
}
return forCollectionViewCell
} else {
let forCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CollectionViewCell
// forCollectionViewCell.button.tag = indexPath.item + 100
if monthData![indexPath.row] == 0 {
forCollectionViewCell.isHidden = true
} else {
forCollectionViewCell.Label.text = String(monthData![indexPath.row])
}
return forCollectionViewCell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView == nextMonthCollectionView {
return .init(width: 53.25 , height: 67)
} else{
return .init(width: 53.25 , height: 67)
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.nextMonthCollectionView {
let forCollectionViewCell = collectionView.cellForItem(at: indexPath) as! NextMonthCollectionViewCell
self.collectionView.reloadData()
collectionView.reloadData()
forCollectionViewCell.Label.textColor = .white
forCollectionViewCell.Label2.backgroundColor = .red
forCollectionViewCell.Label2.layer.cornerRadius = 0.5 * forCollectionViewCell.Label2.bounds.size.width
forCollectionViewCell.Label2.clipsToBounds = true
}else{
let forCollectionViewCell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
self.nextMonthCollectionView.reloadData()
collectionView.reloadData()
forCollectionViewCell.Label.textColor = .white
forCollectionViewCell.Label2.backgroundColor = .red
forCollectionViewCell.Label2.layer.cornerRadius = 0.5 * forCollectionViewCell.Label2.bounds.size.width
forCollectionViewCell.Label2.clipsToBounds = true
}
}
}
and this is my photo. this first photo is before I press any cell.
enter image description here
and this second photo is right after I press 13cell.
I really don't know why this happens.
I searched google looking for this information, but I didn't find an answer.
enter image description here
ps) when I don't use reloadData() function.. I did not get error.. but
I have to use reloadData.. because I have to clean my collectionView and then make a newly selected cell round red cell.

`if nextMonthData![indexPath.row] == 0 {
forCollectionViewCell.isHidden = true
} else {
forCollectionViewCell.isHidden =false
forCollectionViewCell.Label.text = String(nextMonthData![indexPath.row])
}
return forCollectionViewCell
}
`
setting else condition that will solve your problem.
The reason behind it is when collection view dequeuing cell may be that cell is already hidden that's why its disappearing.

Related

How can I update a UICollectionView from another class?

I am trying this for a couple of days now and haven't achieved anything yet. What I am trying to do is when a user picks a User item form the ViewController class, I want to save it in Realm and show it in the CollectionView of the SavedInterestsViewController class. I use a delegate pattern as suggested in this post How to access and refresh a UITableView from another class in Swift, but unfortunately I still receive nil, I guess because the GC removed the collectionView outlet already right? (please correct me if I misunderstood it). However, how can I get this to work by using a delegate pattern? Here is my code, this is the class where the user Picks a new User-item:
protocol ViewControllerDelegate {
func didUpdate(sender: ViewController)
}
class ViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var collectionView: UICollectionView!
var delegate: ViewControllerDelegate?
let numberOfTweets = 5
let realm = try! Realm()
var image = UIImage()
var imageArray: [String] = []
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
searchBar.delegate = self
}
}
extension ViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("One second...")
let functionClass = NetworkingFunctions()
var loopCount = 0
functionClass.getWikipediaAssumptions(for: searchBar.text!) { [self] (articleArray) in
self.userArray.removeAll()
for x in articleArray {
functionClass.performWikipediaSearch(with: x, language: WikipediaLanguage("en")) { (user) in
self.userArray.append(user)
collectionView.reloadData()
loopCount += 1
}
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if userArray[indexPath.item].checked == false {
userArray[indexPath.item].checked = true
collectionView.reloadData()
let newUser = User()
newUser.image = userArray[indexPath.item].image
newUser.name = userArray[indexPath.item].name
newUser.checked = true
try! realm.write {
realm.add(newUser)
}
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
}
else {
userArray[indexPath.item].checked = false
collectionView.reloadData()
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
class User: Object {
#objc dynamic var image: NSData = NSData()
#objc dynamic var name: String = ""
#objc dynamic var checked: Bool = false
}
... and this is the class where I want to show the selected item, after the User clicked on the 'Back' Button of the navigation controller of the ViewController class:
class SavedInterestsViewController: UIViewController, ViewControllerDelegate {
func didUpdate(sender: ViewController) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var collectionView: UICollectionView!
let realm = try! Realm()
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
fetchDataFromRealm()
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "SavedToNew", sender: self)
}
func fetchDataFromRealm() {
userArray.append(contentsOf: realm.objects(User.self))
collectionView.reloadData()
}
}
extension SavedInterestsViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
}
extension SavedInterestsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
in your code you have lines
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
but it do mostly nothing - you set the delegate to newly created class, didUpdate it - but I don't see any use of it - you don't present it in any way.
If I understand you right - you have SavedInterestsViewController, from it - you open ViewController, do something and when back to SavedInterestsViewController. (I can be wrong with your flow - correct me if so)
In this flow - you have delegate property in ViewController, but it must be of type SavedInterestsViewController. And you have to set it to SavedInterestsViewController when you open ViewController from it. And later in ViewController you have to call didUpdate method of delegate.

How can I set my DropDelegate and DragDelegate for my TableView nested in my CollectionView?

I have been working at this for a while. I am not sure if it is the best approach but I have created a collectionView with a custom UICollectionViewCell to include a tableView within. So far everything is working fine, but now I am trying to add drag interaction but can't seem to get that working.
I am trying to achieve having a interactive tableView within each CollectionViewCell if that is possible.
I did try to set my delegates here but it gave me:
Cannot assign value of type 'CommodityCropCardCell' to type 'UITableViewDropDelegate?'
Here is my UICollectionViewCell Code (CommodityCropCardCell):
class CommodityCropCardCell : UICollectionViewCell {
static var identifier : String = "CommodityCropCardCell"
weak var cropCardTableView : UITableView!
var cropItems : [cropCardInputs]!
override init(frame:CGRect){
super.init(frame:frame)
let cropCards = UITableView()
let cropItems : [cropCardInputs] = []
self.contentView.addSubview(cropCards)
self.cropCardTableView = cropCards
self.cropItems = cropItems
cropCards.dataSource = self
cropCards.delegate = self
// cropCards.dragInteractionEnabled = true
// cropCards.dragDelegate = self
// cropCards.dropDelegate = self
cropCards.register(cropCardsCell.self, forCellReuseIdentifier: "cropCardsCell")
cropCards.reloadData()
cropCards.dragInteractionEnabled = true
casesLabel.isHidden = true
self.reset()
}
required init?(coder: NSCoder) {
fatalError("init code error")
}
override func prepareForReuse() {
super.prepareForReuse()
self.reset()
}
func reset(){
print("resetting")
}
}
Here is my CropCardsViewController : UICollectionViewDataSource:
extension CropCardsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionCropCard.dequeueReusableCell(withReuseIdentifier: CommodityCropCardCell.identifier, for: indexPath) as! CommodityCropCardCell
let data = self.data[indexPath.item]
cell.titleLabel.text = data.title
cell.casesLabel.text = "\(data.cases)"
cell.cropItems = data.cards
cell.backgroundColor = .white
cell.layer.cornerRadius = 5.0
cell.layer.masksToBounds = true
return cell
}
}

CollectionViewCell not displaying cells or loading core data string

I am trying to save a core data string via the first class, then load that string into a collectionviewcell textlabel. I am doing all of this without the use of any storyboards. I am not getting any compile errors. It is just when I load this class, nothing is appearing.
This is a link to my git profile https://github.com/redrock34/collectionViewCellLoad.
class ViewController: UIViewController {
var itemsName: [Item] = []
weak var collectionView: UICollectionView!
override func loadView() {
super.loadView()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(collectionView)
NSLayoutConstraint.activate([
self.view.topAnchor.constraint(equalTo: collectionView.topAnchor),
self.view.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor),
self.view.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
self.view.trailingAnchor.constraint(equalTo: collectionView.trailingAnchor),
])
self.collectionView = collectionView
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.register(Cell.self, forCellWithReuseIdentifier: Cell.identifier)
self.collectionView.alwaysBounceVertical = true
self.collectionView.backgroundColor = .brown
collectionView.reloadData()
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return self.itemsName.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.identifier, for: indexPath) as! Cell
let user = itemsName[indexPath.row]
cell.textLabel?.text = ("\nCourse: \(user.atBATS!) Score: ")
cell.backgroundColor = UIColor.blue
cell.textLabel.textColor = UIColor.black
return cell
}
}
You have an empty dataSource
var itemsName: [Item] = []

Multiple Selection on Collection View

I'm having an issue when I'm selecting and deselecting the cell once, it works. But if I select the same cell again nothing happens, it doesn't trigger the didselect function. I also enabled multiple selection. Thank you for the help.
My code for CollectionViewCell:
class EventItemCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var txtLabel: UILabel!
#IBOutlet weak var imageCheck: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
public func toggleSelected() {
if (isSelected == false) {
//Hide check mark image.
self.imageCheck.image = UIImage(named: "success-1")
isSelected = true
}else{
//Show check mark image.
self.imageCheck.image = UIImage(named: "success-2")
isSelected = false
}
}
}
My code for the view controller:
import UIKit
class EventItemSelectionViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
var items: [Item] = [Item(imageName: "vegetables"), Item(imageName: "cheers"), Item(imageName: "cocktail"), Item(imageName: "ice-cream"), Item(imageName: "soup"), Item(imageName: "steak")]
var itemsNames = ["Salades", "Boisson alcoolisée", "Boisson non-alcoolisée", "Dessert", "Entrée", "Viande"]
var itemsCheck = [UIImage(named: "success-2"), UIImage(named: "")]
var collectionViewFlowLayout: UICollectionViewFlowLayout!
let cellIdentifier = "ItemCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.edgesForExtendedLayout = UIRectEdge.bottom
setupCollectionView()
collectionView.allowsMultipleSelection = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupCollectionViewItemSize()
}
private func setupCollectionView(){
collectionView.delegate = self
collectionView.dataSource = self
let nib = UINib(nibName: "EventItemCollectionViewCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
}
private func setupCollectionViewItemSize(){
if collectionViewFlowLayout == nil {
let numberOfItemPerRow: CGFloat = 2
let lineSpacing: CGFloat = 1
let interItemSpacing: CGFloat = 1
let width = (collectionView.frame.width - (numberOfItemPerRow - 1) * interItemSpacing) / numberOfItemPerRow
let height = width
collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.itemSize = CGSize(width: width, height: height)
collectionViewFlowLayout.sectionInset = UIEdgeInsets.zero
collectionViewFlowLayout.scrollDirection = .vertical
collectionViewFlowLayout.minimumLineSpacing = lineSpacing
collectionViewFlowLayout.minimumInteritemSpacing = interItemSpacing
collectionView.setCollectionViewLayout(collectionViewFlowLayout, animated: true)
}
}
}
extension EventItemSelectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCollectionViewCell", for: indexPath) as! EventItemCollectionViewCell
cell.imageView.image = UIImage(named: items[indexPath.item].imageName)
cell.txtLabel.text = itemsNames[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("\(indexPath)")
let cell = collectionView.cellForItem(at: indexPath) as? EventItemCollectionViewCell
cell?.isSelected = true
cell?.toggleSelected()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? EventItemCollectionViewCell
cell?.isSelected = false
cell?.toggleSelected()
}
}
Check this one
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCollectionViewCell", for: indexPath) as! EventItemCollectionViewCell
{
if !itemsNames.contains(indexPath.item) {
cell.backgroundColor = .red
self.itemsNames.append(indexPath.row)
} else {
cell.backgroundColor = .white
self.itemsNames.remove(object: indexPath.item)
}
}
}
But if I select the same cell again nothing happens
as you always set this to true inside didSelectItemAt
cell?.isSelected = true
cell?.toggleSelected()
var selectedArr = [Int]()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForRow(at:indexPath) as! EventItemCollectionViewCell
if !selectedArr.contains(indexPath.item) {
cell.imageCheck.image = UIImage(named: "success-1")
self.selectedArr.append(indexPath.row)
} else {
cell.imageCheck.image = UIImage(named: "success-2")
self.selectedArr.remove(where:{ $0 == indexPath.item })
}
}
}

When searchbar is cancelled, selected row is changing

I created a collection view with search bar. Rows are selectable on this collection view. Search bar is working perfectly when I search something and when I select a row. However when I clicked cancel button of search bar, the selected row is changing. For example, there are 3 row on the collection view. All of them are selectable. I'm searching for 3rd row and I'm selecting it. After the selecting this 3rd row, if I click to cancel button of search bar, selected row is changing and 1st row is being selected row. How can I handle with this issue?
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UISearchControllerDelegate, UISearchBarDelegate {
#IBOutlet weak var collectionView: UICollectionView!
let searchController = UISearchController(searchResultsController: nil)
var things = [Things]()
var filteredThings = [Things]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
CollectionViewController.instance = self
things = [
Things(name: "1", imageName: "firstImage", including: false),
Things(name: "2", imageName: "secondImage", including: false),
Things(name: "3", imageName: "thirdImage", including: false)
]
// Setup the Search Controller
self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search for tools and resources"
searchController.searchBar.sizeToFit()
searchController.searchBar.becomeFirstResponder()
self.navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if isFiltering() {
return filteredThings.count
}
return things.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! CustomCollectionViewCell
let thing: Thing
if isFiltering() {
thing = filteredThings[indexPath.row]
} else {
thing = things[indexPath.row]
}
cell.imageView.image = UIImage(named: thing.imageName)
cell.labelView.text = thing.name
cell.layer.cornerRadius = 7
cell.imageView.layer.cornerRadius = 7
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
var thing: Things
if isFiltering() {
thing = filteredThings[indexPath.row]
} else {
thing = things[indexPath.row]
}
cell?.layer.cornerRadius = 5
cell?.layer.borderWidth = 3
cell?.layer.borderColor = myGreenTabBarColor.cgColor
thing.including = true
print(thing.name)
print(thing.including)
collectionView.allowsMultipleSelection = true
print("This cell is selected")
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
var thing: Things
if isFiltering() {
thing = filteredThings[indexPath.row]
} else {
thing = things[indexPath.row]
}
cell?.layer.cornerRadius = 5
cell?.layer.borderWidth = 3
cell?.layer.borderColor = UIColor.white.cgColor
thing.including = false
print(thing.including)
collectionView.allowsMultipleSelection = true
print("This cell is Deselected")
}
func searchBarIsEmpty() -> Bool {
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.dismiss(animated: true, completion: nil)
collectionView.reloadData()
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filteredThings = things.filter({( thing : Things) -> Bool in
return thing.name.lowercased().contains(searchText.lowercased())
})
collectionView.reloadData()
}
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
}
extension CollectionViewController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
// TODO
filterContentForSearchText(searchController.searchBar.text!)
}
}
Ok, you have 3 rows ("a" , "b", "c")
Then you search for "c"
Now you have 1 row in table with "c"
This row has Indexpath(section = 0, row = 0)
Now you select row with Indexpath(section = 0, row = 0)
cancel search - again 3 rows
And the selected row is the row with Indexpath(section = 0, row = 0). Guess what item is this? ( "a" )
I suppose you should store selected items not indexpaths and make cells selected in cellforrow method