How do I get the current Item of a CollectionViewCell, Using a Button in the Cell?










0















I have a question about finding the selected Item of my CollectionViewCells. I want to bring the Data to another ViewController and then edit and save it to the selected Item of my Cells? The Problem is that there my current Item is alway 0 and so my first CollectionCell? I use for testing a ItemList.txt file.



One of the cells:



One of the Cells



Here is my EditViewController:



class EditViewController: UIViewController 
var itemList = ListItem.load()
didSet
ListItem.save(itemList)



@IBOutlet weak var editTextField: UITextField!
@IBOutlet weak var editView: UIView!

//var currentItem = 0
var currentText = ""
var currentItem = 0

override func viewDidLoad()
super.viewDidLoad()

editTextField.text = itemList[currentItem]

editView.clipsToBounds = true
editView.layer.borderColor = UIColor.black.cgColor
editView.layer.cornerRadius = 25


@IBAction func saveButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


@IBAction func cancelButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
self.editView.endEditing(true)





Here is my CollectionViewCell:



class CollectionViewCell: UICollectionViewCell 
var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()





Here my cellForItemAt in the Main ViewController:



 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true

cell.btnTapAction = () in
print("Edit tapped in cell", indexPath.item)
// start your edit process here...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController
viewController.currentItem = indexPath.item
print("(viewController.currentItem)")


return cell



Here my ViewCollectionViewCell:






class CollectionViewCell: UICollectionViewCell 

var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()







Maybe there is an answer for that, but I didn't find it.










share|improve this question
























  • Are you saying that this line print("Edit tapped in cell", indexPath.item) always prints 0 for indexPath.item, regardless of which cell's button you tap?

    – DonMag
    Nov 15 '18 at 21:26











  • And... do you also have a func editButtonTapped(...) in your Main ViewController? Because it looks like you are adding a .touchUpInside action to the button (in every cell) that calls editButtonTapped(...) in your Main VC instead of calling (or in addition to calling) editButtonTapped(...) in your cell class.

    – DonMag
    Nov 15 '18 at 21:29











  • My editButtonTapoed I have in the CollectionViewCell and when I print the indexPath.item it prints the selected item, so this is working! But when I want to edit the text it is always the first item, it is the zero item!?

    – DKoenig82
    Nov 15 '18 at 21:39











  • Your code shows let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController, and then you set viewController.currentItem = indexPath.item ... but where is the code that's actually showing that view controller?

    – DonMag
    Nov 16 '18 at 14:03











  • The code is the first code snippet!

    – DKoenig82
    Nov 16 '18 at 14:06
















0















I have a question about finding the selected Item of my CollectionViewCells. I want to bring the Data to another ViewController and then edit and save it to the selected Item of my Cells? The Problem is that there my current Item is alway 0 and so my first CollectionCell? I use for testing a ItemList.txt file.



One of the cells:



One of the Cells



Here is my EditViewController:



class EditViewController: UIViewController 
var itemList = ListItem.load()
didSet
ListItem.save(itemList)



@IBOutlet weak var editTextField: UITextField!
@IBOutlet weak var editView: UIView!

//var currentItem = 0
var currentText = ""
var currentItem = 0

override func viewDidLoad()
super.viewDidLoad()

editTextField.text = itemList[currentItem]

editView.clipsToBounds = true
editView.layer.borderColor = UIColor.black.cgColor
editView.layer.cornerRadius = 25


@IBAction func saveButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


@IBAction func cancelButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
self.editView.endEditing(true)





Here is my CollectionViewCell:



class CollectionViewCell: UICollectionViewCell 
var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()





Here my cellForItemAt in the Main ViewController:



 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true

cell.btnTapAction = () in
print("Edit tapped in cell", indexPath.item)
// start your edit process here...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController
viewController.currentItem = indexPath.item
print("(viewController.currentItem)")


return cell



Here my ViewCollectionViewCell:






class CollectionViewCell: UICollectionViewCell 

var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()







Maybe there is an answer for that, but I didn't find it.










share|improve this question
























  • Are you saying that this line print("Edit tapped in cell", indexPath.item) always prints 0 for indexPath.item, regardless of which cell's button you tap?

    – DonMag
    Nov 15 '18 at 21:26











  • And... do you also have a func editButtonTapped(...) in your Main ViewController? Because it looks like you are adding a .touchUpInside action to the button (in every cell) that calls editButtonTapped(...) in your Main VC instead of calling (or in addition to calling) editButtonTapped(...) in your cell class.

    – DonMag
    Nov 15 '18 at 21:29











  • My editButtonTapoed I have in the CollectionViewCell and when I print the indexPath.item it prints the selected item, so this is working! But when I want to edit the text it is always the first item, it is the zero item!?

    – DKoenig82
    Nov 15 '18 at 21:39











  • Your code shows let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController, and then you set viewController.currentItem = indexPath.item ... but where is the code that's actually showing that view controller?

    – DonMag
    Nov 16 '18 at 14:03











  • The code is the first code snippet!

    – DKoenig82
    Nov 16 '18 at 14:06














0












0








0








I have a question about finding the selected Item of my CollectionViewCells. I want to bring the Data to another ViewController and then edit and save it to the selected Item of my Cells? The Problem is that there my current Item is alway 0 and so my first CollectionCell? I use for testing a ItemList.txt file.



One of the cells:



One of the Cells



Here is my EditViewController:



class EditViewController: UIViewController 
var itemList = ListItem.load()
didSet
ListItem.save(itemList)



@IBOutlet weak var editTextField: UITextField!
@IBOutlet weak var editView: UIView!

//var currentItem = 0
var currentText = ""
var currentItem = 0

override func viewDidLoad()
super.viewDidLoad()

editTextField.text = itemList[currentItem]

editView.clipsToBounds = true
editView.layer.borderColor = UIColor.black.cgColor
editView.layer.cornerRadius = 25


@IBAction func saveButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


@IBAction func cancelButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
self.editView.endEditing(true)





Here is my CollectionViewCell:



class CollectionViewCell: UICollectionViewCell 
var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()





Here my cellForItemAt in the Main ViewController:



 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true

cell.btnTapAction = () in
print("Edit tapped in cell", indexPath.item)
// start your edit process here...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController
viewController.currentItem = indexPath.item
print("(viewController.currentItem)")


return cell



Here my ViewCollectionViewCell:






class CollectionViewCell: UICollectionViewCell 

var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()







Maybe there is an answer for that, but I didn't find it.










share|improve this question
















I have a question about finding the selected Item of my CollectionViewCells. I want to bring the Data to another ViewController and then edit and save it to the selected Item of my Cells? The Problem is that there my current Item is alway 0 and so my first CollectionCell? I use for testing a ItemList.txt file.



One of the cells:



One of the Cells



Here is my EditViewController:



class EditViewController: UIViewController 
var itemList = ListItem.load()
didSet
ListItem.save(itemList)



@IBOutlet weak var editTextField: UITextField!
@IBOutlet weak var editView: UIView!

//var currentItem = 0
var currentText = ""
var currentItem = 0

override func viewDidLoad()
super.viewDidLoad()

editTextField.text = itemList[currentItem]

editView.clipsToBounds = true
editView.layer.borderColor = UIColor.black.cgColor
editView.layer.cornerRadius = 25


@IBAction func saveButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


@IBAction func cancelButton(_ sender: Any)
self.dismiss(animated: true, completion: nil)
editTextField.resignFirstResponder()


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
self.editView.endEditing(true)





Here is my CollectionViewCell:



class CollectionViewCell: UICollectionViewCell 
var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()





Here my cellForItemAt in the Main ViewController:



 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true

cell.btnTapAction = () in
print("Edit tapped in cell", indexPath.item)
// start your edit process here...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController
viewController.currentItem = indexPath.item
print("(viewController.currentItem)")


return cell



Here my ViewCollectionViewCell:






class CollectionViewCell: UICollectionViewCell 

var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()







Maybe there is an answer for that, but I didn't find it.






class CollectionViewCell: UICollectionViewCell 

var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()







class CollectionViewCell: UICollectionViewCell 

var btnTapAction : (()->())?

@IBOutlet weak var listLabel: UILabel!
@IBOutlet weak var editButton: UIButton!

required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)

self.layer.cornerRadius = self.frame.size.width * 0.1
self.layer.borderWidth = 0
self.layer.borderColor = UIColor(red: 0.5, green: 0.47, blue: 0.25, alpha: 1.0).cgColor


@IBAction func editButtonTapped(_ sender: UIButton)
print("Tapped!")

btnTapAction?()








ios swift database uicollectionview uicollectionviewcell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 15:14







DKoenig82

















asked Nov 15 '18 at 21:21









DKoenig82DKoenig82

73




73












  • Are you saying that this line print("Edit tapped in cell", indexPath.item) always prints 0 for indexPath.item, regardless of which cell's button you tap?

    – DonMag
    Nov 15 '18 at 21:26











  • And... do you also have a func editButtonTapped(...) in your Main ViewController? Because it looks like you are adding a .touchUpInside action to the button (in every cell) that calls editButtonTapped(...) in your Main VC instead of calling (or in addition to calling) editButtonTapped(...) in your cell class.

    – DonMag
    Nov 15 '18 at 21:29











  • My editButtonTapoed I have in the CollectionViewCell and when I print the indexPath.item it prints the selected item, so this is working! But when I want to edit the text it is always the first item, it is the zero item!?

    – DKoenig82
    Nov 15 '18 at 21:39











  • Your code shows let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController, and then you set viewController.currentItem = indexPath.item ... but where is the code that's actually showing that view controller?

    – DonMag
    Nov 16 '18 at 14:03











  • The code is the first code snippet!

    – DKoenig82
    Nov 16 '18 at 14:06


















  • Are you saying that this line print("Edit tapped in cell", indexPath.item) always prints 0 for indexPath.item, regardless of which cell's button you tap?

    – DonMag
    Nov 15 '18 at 21:26











  • And... do you also have a func editButtonTapped(...) in your Main ViewController? Because it looks like you are adding a .touchUpInside action to the button (in every cell) that calls editButtonTapped(...) in your Main VC instead of calling (or in addition to calling) editButtonTapped(...) in your cell class.

    – DonMag
    Nov 15 '18 at 21:29











  • My editButtonTapoed I have in the CollectionViewCell and when I print the indexPath.item it prints the selected item, so this is working! But when I want to edit the text it is always the first item, it is the zero item!?

    – DKoenig82
    Nov 15 '18 at 21:39











  • Your code shows let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController, and then you set viewController.currentItem = indexPath.item ... but where is the code that's actually showing that view controller?

    – DonMag
    Nov 16 '18 at 14:03











  • The code is the first code snippet!

    – DKoenig82
    Nov 16 '18 at 14:06

















Are you saying that this line print("Edit tapped in cell", indexPath.item) always prints 0 for indexPath.item, regardless of which cell's button you tap?

– DonMag
Nov 15 '18 at 21:26





Are you saying that this line print("Edit tapped in cell", indexPath.item) always prints 0 for indexPath.item, regardless of which cell's button you tap?

– DonMag
Nov 15 '18 at 21:26













And... do you also have a func editButtonTapped(...) in your Main ViewController? Because it looks like you are adding a .touchUpInside action to the button (in every cell) that calls editButtonTapped(...) in your Main VC instead of calling (or in addition to calling) editButtonTapped(...) in your cell class.

– DonMag
Nov 15 '18 at 21:29





And... do you also have a func editButtonTapped(...) in your Main ViewController? Because it looks like you are adding a .touchUpInside action to the button (in every cell) that calls editButtonTapped(...) in your Main VC instead of calling (or in addition to calling) editButtonTapped(...) in your cell class.

– DonMag
Nov 15 '18 at 21:29













My editButtonTapoed I have in the CollectionViewCell and when I print the indexPath.item it prints the selected item, so this is working! But when I want to edit the text it is always the first item, it is the zero item!?

– DKoenig82
Nov 15 '18 at 21:39





My editButtonTapoed I have in the CollectionViewCell and when I print the indexPath.item it prints the selected item, so this is working! But when I want to edit the text it is always the first item, it is the zero item!?

– DKoenig82
Nov 15 '18 at 21:39













Your code shows let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController, and then you set viewController.currentItem = indexPath.item ... but where is the code that's actually showing that view controller?

– DonMag
Nov 16 '18 at 14:03





Your code shows let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController, and then you set viewController.currentItem = indexPath.item ... but where is the code that's actually showing that view controller?

– DonMag
Nov 16 '18 at 14:03













The code is the first code snippet!

– DKoenig82
Nov 16 '18 at 14:06






The code is the first code snippet!

– DKoenig82
Nov 16 '18 at 14:06













1 Answer
1






active

oldest

votes


















0














Your approach is not-quite-right.



In your .btnTapAction closure, you create a new instance of EditViewController. However, as soon as that closure exits, that instance no longer exists.



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// here, the closure exits, and
// viewController no longer exists!



At the same time you are running that code, your Segue is creating its own instance of EditViewController.



That's why .currentItem is always Zero.



Instead, you need to save the indexPath.item in a class-level variable, and then set .currentItem inside prepare(for segue: ...):



class YourCollectionViewController: UICollectionViewController 

var selectedItem = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?)

if let newEditVC = segue.destination as? EditViewController
newEditVC.currentItem = self.selectedItem




func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true


cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

// set your class-level variable
// which will be used in prepare(for segue: ...)
self.selectedItem = indexPath.item


return cell






Or, another approach... Delete the Segue from Storyboard, and change your .btnTapAction to this:



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// present that instance of EditViewController
self.present(viewController, animated: true, completion: nil)






share|improve this answer























  • Thank you very very very much! It is now working!

    – DKoenig82
    Nov 16 '18 at 16:33










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328062%2fhow-do-i-get-the-current-item-of-a-collectionviewcell-using-a-button-in-the-cel%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Your approach is not-quite-right.



In your .btnTapAction closure, you create a new instance of EditViewController. However, as soon as that closure exits, that instance no longer exists.



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// here, the closure exits, and
// viewController no longer exists!



At the same time you are running that code, your Segue is creating its own instance of EditViewController.



That's why .currentItem is always Zero.



Instead, you need to save the indexPath.item in a class-level variable, and then set .currentItem inside prepare(for segue: ...):



class YourCollectionViewController: UICollectionViewController 

var selectedItem = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?)

if let newEditVC = segue.destination as? EditViewController
newEditVC.currentItem = self.selectedItem




func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true


cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

// set your class-level variable
// which will be used in prepare(for segue: ...)
self.selectedItem = indexPath.item


return cell






Or, another approach... Delete the Segue from Storyboard, and change your .btnTapAction to this:



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// present that instance of EditViewController
self.present(viewController, animated: true, completion: nil)






share|improve this answer























  • Thank you very very very much! It is now working!

    – DKoenig82
    Nov 16 '18 at 16:33















0














Your approach is not-quite-right.



In your .btnTapAction closure, you create a new instance of EditViewController. However, as soon as that closure exits, that instance no longer exists.



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// here, the closure exits, and
// viewController no longer exists!



At the same time you are running that code, your Segue is creating its own instance of EditViewController.



That's why .currentItem is always Zero.



Instead, you need to save the indexPath.item in a class-level variable, and then set .currentItem inside prepare(for segue: ...):



class YourCollectionViewController: UICollectionViewController 

var selectedItem = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?)

if let newEditVC = segue.destination as? EditViewController
newEditVC.currentItem = self.selectedItem




func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true


cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

// set your class-level variable
// which will be used in prepare(for segue: ...)
self.selectedItem = indexPath.item


return cell






Or, another approach... Delete the Segue from Storyboard, and change your .btnTapAction to this:



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// present that instance of EditViewController
self.present(viewController, animated: true, completion: nil)






share|improve this answer























  • Thank you very very very much! It is now working!

    – DKoenig82
    Nov 16 '18 at 16:33













0












0








0







Your approach is not-quite-right.



In your .btnTapAction closure, you create a new instance of EditViewController. However, as soon as that closure exits, that instance no longer exists.



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// here, the closure exits, and
// viewController no longer exists!



At the same time you are running that code, your Segue is creating its own instance of EditViewController.



That's why .currentItem is always Zero.



Instead, you need to save the indexPath.item in a class-level variable, and then set .currentItem inside prepare(for segue: ...):



class YourCollectionViewController: UICollectionViewController 

var selectedItem = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?)

if let newEditVC = segue.destination as? EditViewController
newEditVC.currentItem = self.selectedItem




func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true


cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

// set your class-level variable
// which will be used in prepare(for segue: ...)
self.selectedItem = indexPath.item


return cell






Or, another approach... Delete the Segue from Storyboard, and change your .btnTapAction to this:



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// present that instance of EditViewController
self.present(viewController, animated: true, completion: nil)






share|improve this answer













Your approach is not-quite-right.



In your .btnTapAction closure, you create a new instance of EditViewController. However, as soon as that closure exits, that instance no longer exists.



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// here, the closure exits, and
// viewController no longer exists!



At the same time you are running that code, your Segue is creating its own instance of EditViewController.



That's why .currentItem is always Zero.



Instead, you need to save the indexPath.item in a class-level variable, and then set .currentItem inside prepare(for segue: ...):



class YourCollectionViewController: UICollectionViewController 

var selectedItem = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?)

if let newEditVC = segue.destination as? EditViewController
newEditVC.currentItem = self.selectedItem




func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.listLabel.text = itemList[indexPath.row]

cell.editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControl.Event.touchUpInside)
cell.editButton.tag = indexPath.item
cell.editButton.isUserInteractionEnabled = true


cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

// set your class-level variable
// which will be used in prepare(for segue: ...)
self.selectedItem = indexPath.item


return cell






Or, another approach... Delete the Segue from Storyboard, and change your .btnTapAction to this:



 cell.btnTapAction = () in
// you tapped the button
// this line prints the indexPath.item to the console
print("Edit tapped in cell", indexPath.item)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// here, you create an instance of EditViewController
let viewController = storyboard.instantiateViewController(withIdentifier: "edit") as! EditViewController

// here, you set .currentItem in the instance of EditViewController
viewController.currentItem = indexPath.item

// you print that value to the console
print("(viewController.currentItem)")

// present that instance of EditViewController
self.present(viewController, animated: true, completion: nil)







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 15:14









DonMagDonMag

17.2k21030




17.2k21030












  • Thank you very very very much! It is now working!

    – DKoenig82
    Nov 16 '18 at 16:33

















  • Thank you very very very much! It is now working!

    – DKoenig82
    Nov 16 '18 at 16:33
















Thank you very very very much! It is now working!

– DKoenig82
Nov 16 '18 at 16:33





Thank you very very very much! It is now working!

– DKoenig82
Nov 16 '18 at 16:33



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328062%2fhow-do-i-get-the-current-item-of-a-collectionviewcell-using-a-button-in-the-cel%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Top Tejano songwriter Luis Silva dead of heart attack at 64

ReactJS Fetched API data displays live - need Data displayed static

政党