Programmatically Setting UIButton Font Removes "background Configuration" Section - swift

I am attempting to change my font for my UIButton programmatically because it is in a UICollectionView. When I do this however, it removes the "background configuration" in the Attributes Inspector, an example is shown here. The reason why is because the text has to be set to "default" in order for the font to shown from the code. I need that area in order to add a corner style. I have shown my code below In which I have tried to programmatically add a corner style to no luck.
The attempted code specifically is in the "if" statement towards the bottom.
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionViewButtons: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionViewButtons.delegate = self
collectionViewButtons.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6 //number of buttons
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ButtonCollectionViewCell
cell.buttonLive.setTitle("Handling a Breakup", for: .normal) //set button title
cell.buttonLive.titleLabel!.font = UIFont(name: "Marker Felt", size: 20)
_ = UIButton.Configuration.CornerStyle.large
if indexPath.item == 0 { //first button
cell.buttonLive.backgroundColor = UIColor.darkGray //set button background
}
else if indexPath.item == 1 { //second button
cell.buttonLive.backgroundColor = UIColor.systemGray
cell.buttonLive.setTitle("Good Work", for: .normal)
}
else if indexPath.item == 2 { //3rd button
cell.buttonLive.backgroundColor = UIColor.darkGray
}
else { // for remaining buttons
cell.buttonLive.backgroundColor = UIColor.darkGray
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0 { // opens any page by clicking button 1
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC1") as! ViewController1
// navigationController?.pushViewController(vc, animated: true)
// }
// else if indexPath.item == 1 {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC2") as! ViewController2
// navigationController?.pushViewController(vc, animated: true)
}
// else if indexPath.item == 2 {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC3") as! ViewController3
// navigationController?.pushViewController(vc, animated: true)
}
// else {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC4") as! ViewController4
// navigationController?.pushViewController(vc, animated: true)
}
// }
//}
// You can return any number of buttons by changing return 6 to any required num

Use switch statement, this is how your collection view cellForItemAt look like:
cell.myButton.setTitle("Handling a Breakup", for: .normal) //set button title
cell.myButton.titleLabel?.font = UIFont(name: "Marker Felt", size: 20)
cell.myButton.layer.cornerRadius = 10
cell.myButton.clipsToBounds = true
switch indexPath.item {
case 1:
cell.myButton.backgroundColor = .link // add your color
cell.myButton.setTitle("Good Work", for: .normal)
default:
cell.myButton.backgroundColor = .white // add your color
}
return cell

Related

Adding a Second CollectionView

In my attempt to add a second CollectionView I have became lost. Here is my future project and I was essentially trying to duplicate that (The reason for the Second collectionView is so that I will have 4 rows, but the top two and bottom two will scroll independently).
Here is the storyboard for reference.
I however get this error here (Second Photo): here
Here is my code for the originally ViewController (WORKING)
Followed by the SecondViewController code, which has caused the app to display the message above.
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet var collectionViewButtons: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionViewButtons.delegate = self
collectionViewButtons.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6 //number of buttons
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ButtonCollectionViewCell
cell.buttonLive.setTitle("Handling a Breakup", for: .normal) //set button title
cell.buttonLive.titleLabel!.font = UIFont(name: "Marker Felt", size: 20)
cell.buttonLive.layer.cornerRadius = 10
cell.buttonLive.clipsToBounds = true
cell.buttonLive.layer.borderWidth = 1.0
cell.buttonLive.layer.borderColor = UIColor.white.cgColor
if indexPath.item == 0 { //first button
cell.buttonLive.backgroundColor = UIColor.darkGray //set button background
}
else if indexPath.item == 1 { //second button
cell.buttonLive.backgroundColor = UIColor.systemGray
cell.buttonLive.setTitle("Good Work", for: .normal)
}
else if indexPath.item == 2 { //3rd button
cell.buttonLive.backgroundColor = UIColor.darkGray
}
else { // for remaining buttons
cell.buttonLive.backgroundColor = UIColor.darkGray
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0 { // opens any page by clicking button 1
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC1") as! ViewController1
// navigationController?.pushViewController(vc, animated: true)
// }
// else if indexPath.item == 1 {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC2") as! ViewController2
// navigationController?.pushViewController(vc, animated: true)
}
// else if indexPath.item == 2 {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC3") as! ViewController3
// navigationController?.pushViewController(vc, animated: true)
}
// else {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC4") as! ViewController4
// navigationController?.pushViewController(vc, animated: true)
}
// }
//}
// You can return any number of buttons by changing return 6 to any required num
SECOND VIEW CONTROLLER:
import UIKit
class SecondViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6 //number of buttons
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let SecondCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SecondCell", for: indexPath) as! ButtonCollectionViewCell
SecondCell.buttonTwo.setTitle("Handling a Breakup", for: .normal) //set button title
SecondCell.buttonLive.titleLabel!.font = UIFont(name: "Marker Felt", size: 20)
SecondCell.buttonTwo.layer.cornerRadius = 10
SecondCell.buttonTwo.clipsToBounds = true
SecondCell.buttonTwo.layer.borderWidth = 1.0
SecondCell.buttonTwo.layer.borderColor = UIColor.white.cgColor
if indexPath.item == 0 { //first button
SecondCell.buttonTwo.backgroundColor = UIColor.darkGray //set button background
}
else if indexPath.item == 1 { //second button
SecondCell.buttonTwo.backgroundColor = UIColor.systemGray
SecondCell.buttonTwo.setTitle("Good Work", for: .normal)
}
else if indexPath.item == 2 { //3rd button
SecondCell.buttonTwo.backgroundColor = UIColor.darkGray
}
else { // for remaining buttons
SecondCell.buttonTwo.backgroundColor = UIColor.darkGray
}
return SecondCell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0 { // opens any page by clicking button 1
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC1") as! ViewController1
// navigationController?.pushViewController(vc, animated: true)
// }
// else if indexPath.item == 1 {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC2") as! ViewController2
// navigationController?.pushViewController(vc, animated: true)
}
// else if indexPath.item == 2 {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC3") as! ViewController3
// navigationController?.pushViewController(vc, animated: true)
}
// else {
// let vc = storyboard?.instantiateViewController(withIdentifier: "anyVC4") as! ViewController4
// navigationController?.pushViewController(vc, animated: true)
}
// }
//}
// You can return any number of buttons by changing return 6 to any required num
Notes:
I have also gone through and done the following to no success:
Changed all "collectionView" writings to say "SecondCollection" because that is what my second collectionView is named.
I have set a Collection IBOutlet for both collectionView.
I have set a separate IBOutlet for both buttons.
If you want two (or more) collection views, you don't want two controllers... you need to check which collection view is requesting data (or being interacted with) and return the appropriate information.
So, your class will look something like this:
class TwoCollectionsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var firstCV: UICollectionView!
#IBOutlet var secondCV: UICollectionView!
let firstData: [String] = [
"Btn 1", "Btn 2", "Btn 3", "Btn 4", "Btn 5",
]
let secondData: [String] = [
"Second 1", "Second 2", "Second 3", "Second 4"
]
override func viewDidLoad() {
super.viewDidLoad()
firstCV.dataSource = self
firstCV.delegate = self
secondCV.dataSource = self
secondCV.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// if it's the First Collection View
if collectionView == firstCV {
return firstData.count
}
// it's not the First Collection View, so it's the Second one
return secondData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// if it's the First Collection View
if collectionView == firstCV {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "firstCell", for: indexPath) as! FirstCollectionViewCell
cell.buttonOne.setTitle(firstData[indexPath.item], for: [])
return cell
}
// it's not the First Collection View, so it's the Second one
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "secondCell", for: indexPath) as! SecondCollectionViewCell
cell.buttonTwo.setTitle(secondData[indexPath.item], for: [])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// if it's the First Collection View
if collectionView == firstCV {
// do what you want because a cell in the First Collection View was selected
return
}
// it's not the First Collection View, so it's the Second one
// do what you want because a cell in the Second Collection View was selected
}
}

Why does my like button like all my images when I only liked one image?

I have this collection view with all these images in my VC. When I tap on one of them another VC opens up and I can tap on a button to like the image which is indicated by the button changing its image. The problem Im having is that all the other images are getting changed too. How would I specifically just like the one image I tapped on and not all of them. Here is the code Im working with:
//First VC
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as!
CustomCollectionViewCell
//shows text
cell.nameLbl.text = heroes[indexPath.row].localized_name.capitalized
cell.nameLbl.adjustsFontSizeToFitWidth = true
//shows images
let defaultLink = "https://api.opendota.com"
let completeLink = defaultLink + heroes[indexPath.row].img
print("This is my\(completeLink)")
cell.imageView.downloaded(from: completeLink)
cell.imageView.isUserInteractionEnabled = true
//shows the num of how many heroes there are
let heroCount = heroes.count
howManyHerosLabel.text = String(describing: heroCount)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let completeLink = defaultLink + heroes[indexPath.item].img//this will return the exact string for selected cell
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewController") as! HeroViewController
secondViewController.completeLink2 = completeLink
secondViewController.completeLink3 = heroes[indexPath.item].localized_name.capitalized
self.present(secondViewController, animated: true, completion: nil)
print("the title of the image is \(completeLink)")
}
//Second VC
override func viewDidLoad() {
super.viewDidLoad()
if UserDefaults.standard.bool(forKey: "Change") {
likedButton.setImage(UIImage(named: "selected_star"), for: .normal)
}
//returns image and text that was presssed on in the VC
heroImageView2.downloaded(from: completeLink2)
labelForHero!.text = completeLink3
}
#IBAction func addToLikes(_ sender: Any) {
//progressView.isHidden = false
UserDefaults.standard.set(true, forKey: "Change")
likedButton.setImage(UIImage(named: "selected_star"), for: .normal)
}
You need to have unique values to identify if its liked or unliked
UserDefaults.standard.set(true, forKey: "Change")
For now .. you are checking against change ... once set to true will remain true ...
My suggestion is to pass heroes[indexPath.item].img to other controller and set UserDefault against this value

I really don't know why my collectionViewCell disappear

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.

UICollectionViewCell delegate won't fire

I'm obviously doing something wrong but unable as of yet to determine where. I setup the cell as follows:
protocol PropertyPhotoCellDelegate: class {
func deletePropertyPhoto(cell: PropertyPhotoCell)
}
class PropertyPhotoCell: UICollectionViewCell {
weak var propertyPhotoCellDelegate: PropertyPhotoCellDelegate?
let deleteButton: UIButton = {
let button = UIButton()
let image = UIImage(named: "delete.png")
button.setImage(image, for: .normal)
button.showsTouchWhenHighlighted = true
button.isHidden = true
button.addTarget(self, action: #selector(handleDeleteButton), for: .touchUpInside)
return button
}()
var isEditing: Bool = false {
didSet {
deleteButton.isHidden = !isEditing
}
}
I've omitted setting up the cell views. Here is the selector
#objc fileprivate func handleDeleteButton() {
propertyPhotoCellDelegate?.deletePropertyPhoto(cell: self)
}
In the UICollectionViewController, I assign the delegate
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! PropertyPhotoCell
cell.photoImageView.image = photos[indexPath.item]
cell.propertyPhotoCellDelegate = self
return cell
}
This hides or shows the delete button on the cell for all the cells in view
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
navigationItem.rightBarButtonItem?.isEnabled = !editing
if let indexPaths = collectionView?.indexPathsForVisibleItems {
for indexPath in indexPaths {
if let cell = collectionView?.cellForItem(at: indexPath) as? PropertyPhotoCell {
cell.deleteButton.isHidden = !isEditing
}
}
}
}
And finally, conforming to the protocol here
extension PropertyPhotosController: PropertyPhotoCellDelegate {
func deletePropertyPhoto(cell: PropertyPhotoCell) {
if let indexPath = collectionView?.indexPath(for: cell) {
photos.remove(at: indexPath.item)
collectionView?.deleteItems(at: [indexPath])
}
}
}
I tap the UICollectionViewController Edit button and all the cells show the delete button as expected. Any of the cell's delete button highlights on tap, but I don't see the delegate getting called.
When the delegate is assigned in the UICollectionViewController, also set the selector for the cell.
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! PropertyPhotoCell
cell.photoImageView.image = photos[indexPath.item]
cell.propertyPhotoCellDelegate = self
cell.deleteButton.addTarget(cell, action: #selector(cell.handleDeleteButton), for: .touchUpInside)
cell.deleteButton.isHidden = true
return cell
}

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