button inside cellView I can't know which cell user pressed - swift

I have custom cell in tableView
inside it I have a button , I want when user click on the button push viewController, how I can do that and how I can know which cell user use its button, because here not didSelectRowAtIndexPath

Create a custom button class
class CustomButton: UIButton {
var indexPath: NSIndexPath!
}
In your custom cell create the button of the CustomButton type add the following lines in cellForRowAtIndexPath
cell.yourCustomButton.indexPath = indexPath
Define IBAction like this
#IBAction func customButtonClicked(sender: CustomButton) {
let indexPath: NSIndexPath = sender.indexPath
// Do whatever you want with the indexPath
}

Add Tag of button in Cell and add Target for your transition Function
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! CustomCell
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector( self.transitonMethod ), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
Fetch indexPath from tag of sender Button and Fetch Cell for this indexPath.Push your controller on your navigation controller
func transitonMethod(sender: AnyObject){
let indexPath = NSIndexPath.init(index: sender.tag)
let cell = tableView.cellForRowAtIndexPath(indexPath)
self.navigationController?.pushViewController(yourController, animated: true)
}

In cellforRow method of tableview:
1) set tag of your button e.g. yourButton.tag = indexpath.row
2) set target method of yourbutton e.g.buttonPressed(sender:UIButton)
3) Now in that target method you will get indexpath.row by sender.tag

Declare an IBAction as follow as suggested in IOS 7 - How to get the indexPath from button placed in UITableViewCell :
#IBAction func didTapOnButton(sender: UIButton) {
let cell: UITableViewCell = sender.superview as! UITableViewCell
let indexPath: NSIndexPath = self.tableView.indexPathForCell(cell)
// Do anything with the indexPath
}
Or the other method :
#IBAction func didTapOnButton(sender: UIButton) {
let center: CGPoint = sender.center
let rootViewPoint: CGPoint = sender.superview?.convertPoint(center, toView: tableView)
let indexPath: NSIndexPath = tableView.indexPathForRowAtPoint(rootViewPoint!)
print(indexPath)
}
Then work with that indexPath to do whatever you need.

Related

How to give xib cell button action in HomeVC in swift

I have created xib collectionview cell.. and i am able to use all its values in HomeVC like below
class HomeVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
#IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "MainCollectionViewCell", bundle: nil)
collectionView.registerNib(nib, forCellWithReuseIdentifier: "MainCollectionViewCell")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCollectionViewCell", forIndexPath: indexPath) as! MainCollectionViewCell
cell.arrivingLabel.text = indexData.arriv
cell.lblDiscountedPrice.text = indexData.discPrice
return cell
}
like below i can give action to xib cell button, but i want xib cell button action in HomeVC class how, please guide me here
cell.btnDetails.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
#objc func connected(sender: UIButton){
}
i want like this in HomeVC
#IBAction func productDetailsMain(_ sender: UIButton){
}
note: if i use same collectionview cell then if i drag from HomeVC button action outlet to collectionview cell button then its adding.. but if i use xib cell in collectionview then this process is not working.. how to give xib cell button action in HomeVC class
You have to use closure.
cell class add this property
var connectionButtonAction: (() -> Void)?
and on the button action make this
#objc func connected(sender: UIButton){
connectionButtonAction?()
}
so finally for on the cell creation you have add this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCollectionViewCell", forIndexPath: indexPath) as! MainCollectionViewCell
cell.arrivingLabel.text = indexData.arriv
cell.lblDiscountedPrice.text = indexData.discPrice
cell.connectionButtonAction = { [weak self] in
print("cell button pressed")
}
return cell
}
I think this is the simple way, but also you get the same approach using delegates.
If you want to have the collection view cell's button trigger an action in the view controller that own's the collection view, you need to add the view controller as the target. You can do that in your cellForItemAtIndexPath, but you will need to remove the previous target/action so you don't keep adding a new target/action each time you reuse a cell:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCollectionViewCell", forIndexPath: indexPath) as! MainCollectionViewCell
cell.arrivingLabel.text = indexData.arriv
cell.lblDiscountedPrice.text = indexData.discPrice
// Remove the previous target/action, if any
cell.btnDetails.removeTarget(nil, action: nil,for: .allEvents)
// Add a new target/action pointing to the method `productDetailsMain(_:)`
cell.btnDetails.addTarget(self, action: #selector(productDetailsMain(_:)), for: .touchUpInside)
return cell
}
You could also set up your cells to hold a closure as in luffy_064's answer.
Note that if you are running on iOS 14 or later, you can use the new addAction(_:for:) method of UIControl to add a UIAction to your button. (UIActions include a closure.)
That might look like this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCollectionViewCell", forIndexPath: indexPath) as! MainCollectionViewCell
cell.arrivingLabel.text = indexData.arriv
cell.lblDiscountedPrice.text = indexData.discPrice
// Remove the previous target/action, if any
let identifier = UIAction.Identifier("button")
removeAction(identifiedBy: identifier, for: .allEvents)
// Add a new UIAction to the button for this cell
let action = UIAction(title: "", image: nil, identifier: identifier, discoverabilityTitle: nil, attributes: [], state: .on) { (action) in
print("You tapped button \(indexPath.row)")
// Your action code here
}
cell(action, for: .touchUpInside)
return cell
}

Field an UITextField when button tapped in a UICollectionView

I gonna need your help to understand how to interact with an UITextField when button tapped.
This is my code in my ViewController:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
cell.addBookTapped.addTarget(self,action: #selector(buttonTapped(_:)),for: .touchUpInside)
cell.configureCell(with: books[indexPath.row], indexCell: indexPath.row )
return cell
}
func buttonTapped(_ sender: UIButton)
{
let tag = sender.tag
//Do Stuff
}
And in my MyCollectionViewCell, I configure all the button and textView and add tag in my button:
#IBOutlet weak var myTextFielThatIWantToFieldWhenButtonTapped: UITextField!
In my ViewController inside my func buttonTapped I can't reach myTextFielThatIWantToFieldWhenButtonTapped.
How can write something in it when the button is tapped and be visible directly on the view?
you have to get your intended cell by calling cellForItem at an indexPath of your specific cell like below: (for example your cell is in section 0 item 0 )
let indexPath = IndexPath(item: 0, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as? YourCustomCollectionViewCellClass
then you can access your variables inside your cell class :
cell.myTextFielThatIWantToFieldWhenButtonTapped

Get indexPath in UITableViewCell subclass

I have a subclass of UITableViewCell that is shown in a TableView. Each cell has a text field. When the textFieldDidEndEditing func is called, I want to save the entered text as an attribute of an NSManagedObject in my Managed Object Context.
This function is implemented in my tableViewCell class:
func textFieldDidEndEditing(textField: UITextField) {
let viewController = ViewController()
let indexPath: NSIndexPath!
viewController.updateCommitsInMOC(self, atIndexPath: indexPath!)
}
And this is the function it calls. This function is implemented in my ViewController class, the one that controls the TableView which is made up of the tableViewCells:
func updateCommitsInMOC(cell: CommitTableViewCell, atIndexPath indexPath: NSIndexPath) {
// Fetch Commit
let commit = fetchedResultsController.objectAtIndexPath(indexPath) as! Commit
// Update Cell
commit.contents = cell.commitContents.text!
if cell.repeatStatus.selectedSegmentIndex == 1 { commit.repeatStatus = true }
saveManagedObjectContext()
}
I'm of course open to any suggestions as to other ways to implement the saving behavior every time the user is done editing the text field.
Is your question "How do I get the IndexPath"? Instead of the UITableviewCell trying to figure out what it's indexPath is in textFieldDidEndEditing, why don't you just figure it out within updateCommitsInMOC function?
Assuming you have a reference to your tableView you can just do this
func updateCommitsInMOC(cell: CommitTableViewCell) {
guard let indexPath = tableView.indexPathForCell(cell) else {
return
}
// Fetch Commit
let commit = fetchedResultsController.objectAtIndexPath(indexPath) as! Commit
// Update Cell
commit.contents = cell.commitContents.text!
if cell.repeatStatus.selectedSegmentIndex == 1 { commit.repeatStatus = true }
saveManagedObjectContext()
}
You can add a tag as row in cell textField.
like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("idCell")
cell.textField.tag = indexPath.row
return cell
}
and the textField delegate:
func textFieldDidEndEditing(textField: UITextField) {
let viewController = ViewController()
let indexPath = NSIndexPath(forRow: textField.tag, section: 0)
viewController.updateCommitsInMOC(self, atIndexPath: indexPath!)
}
or you can use the superview:
func textFieldDidEndEditing(textField: UITextField) {
let view = textField.superview!
let cell = view.superview as! UITableViewCell
let viewController = ViewController()
let indexPath = itemTable.indexPathForCell(cell)
viewController.updateCommitsInMOC(self, atIndexPath: indexPath!)
}
I suggest you to use in your tableview the
setEditing(editing, animated: animated) method.
Then inside of it you can manage the single object retrieving it from the fetchResultController.indexPathForObject(inputObject) or as you used fetchedResultsController.objectAtIndexPath(indexPath).
Finally you can use self.managedObjectContext.saveToPersistentStore() or self.managedObjectContext.save().

Tap on cell and get index

When i tap on a cell i want to receive the index or other identifier specific to that cell. The code works and goes in the tapped function. But how can i receive a index or something like that?
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ShowCell", forIndexPath: indexPath) as UICollectionViewCell
if cell.gestureRecognizers?.count == nil {
let tap = UITapGestureRecognizer(target: self, action: "tapped:")
tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
cell.addGestureRecognizer(tap)
}
return cell
}
func tapped(sender: UITapGestureRecognizer) {
print("tap")
}
Swift 4 - 4.2 - Returns index of tapped cell.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cellIndex = indexPath[1] // try without [1] returns a list.
print(indexPath[1])
chapterIndexDelegate.didTapChapterSelection(chapterIndex: test)
}
Build on Matts answer
first off we add the tap recognizer
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapped(tapGestureRecognizer:)))
cell.textView.addGestureRecognizer(tap)
Then we use the following function to get the indexPath
#objc func tapped(tapGestureRecognizer: UITapGestureRecognizer){
//textField or what ever view you decide to have the tap recogniser on
if let textField = tapGestureRecognizer.view as? UITextField {
// get the cell from the textfields superview.superview
// textField.superView would return the content view within the cell
if let cell = textField.superview?.superview as? UITableViewCell{
// tableview we defined either in storyboard or globally at top of the class
guard let indexPath = self.tableView.indexPath(for: cell) else {return}
print("index path =\(indexPath)")
// then finally if you wanted to pass the indexPath to the main tableView Delegate
self.tableView(self.tableView, didSelectRowAt: indexPath)
}
}
}
Think about it. The sender is the tap gesture recognizer. The g.r.'s view is the cell. Now you can ask the collection view what the index path of this cell is (indexPathForCell:).

How to access the content of a custom cell in swift using button tag?

I have an app that has a custom button in a custom cell. If you select the cell it segues to the a detail view, which is perfect. If I select a button in a cell, the code below prints the cell index into the console.
I need to access the contents of the selected cell (Using the button) and add them to an array or dictionary. I am new to this so struggling to find out how to access the contents of the cell. I tried using didselectrowatindexpath, but I don't know how to force the index to be that of the tag...
So basically, if there are 3 cells with 'Dog', 'Cat', 'Bird' as the cell.repeatLabel.text in each cell and I select the buttons in the rows 1 and 3 (Index 0 and 2), it should add 'Dog' and 'Bird' to the array/dictionary.
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postsCollection.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
// Configure the cell...
var currentRepeat = postsCollection[indexPath.row]
cell.repeatLabel?.text = currentRepeat.product
cell.repeatCount?.text = "Repeat: " + String(currentRepeat.currentrepeat) + " of " + String(currentRepeat.totalrepeat)
cell.accessoryType = UITableViewCellAccessoryType.DetailDisclosureButton
cell.checkButton.tag = indexPath.row;
cell.checkButton.addTarget(self, action: Selector("selectItem:"), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func selectItem(sender:UIButton){
println("Selected item in row \(sender.tag)")
}
OPTION 1. Handling it with delegation
The right way of handling events fired from your cell's subviews is to use delegation.
So you can follow the steps:
1. Above your class definition write a protocol with a single instance method inside your custom cell:
protocol CustomCellDelegate {
func cellButtonTapped(cell: CustomCell)
}
2. Inside your class definition declare a delegate variable and call the protocol method on the delegate:
var delegate: CustomCellDelegate?
#IBAction func buttonTapped(sender: AnyObject) {
delegate?.cellButtonTapped(self)
}
3. Conform to the CustomCellDelegate in the class where your table view is:
class ViewController: CustomCellDelegate
4. Set your cell's delegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell
cell.delegate = self
return cell
}
5. Implement the required method in your view controller class.
EDIT: First define an empty array and then modify it like this:
private var selectedItems = [String]()
func cellButtonTapped(cell: CustomCell) {
let indexPath = self.tableView.indexPathForRowAtPoint(cell.center)!
let selectedItem = items[indexPath.row]
if let selectedItemIndex = find(selectedItems, selectedItem) {
selectedItems.removeAtIndex(selectedItemIndex)
} else {
selectedItems.append(selectedItem)
}
}
where items is an array defined in my view controller:
private let items = ["Dog", "Cat", "Elephant", "Fox", "Ant", "Dolphin", "Donkey", "Horse", "Frog", "Cow", "Goose", "Turtle", "Sheep"]
OPTION 2. Handling it using closures
I've decided to come back and show you another way of handling these type of situations. Using a closure in this case will result in less code and you'll achieve your goal.
1. Declare a closure variable inside your cell class:
var tapped: ((CustomCell) -> Void)?
2. Invoke the closure inside your button handler.
#IBAction func buttonTapped(sender: AnyObject) {
tapped?(self)
}
3. In tableView(_:cellForRowAtIndexPath:) in the containing view controller class :
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
cell.tapped = { [unowned self] (selectedCell) -> Void in
let path = tableView.indexPathForRowAtPoint(selectedCell.center)!
let selectedItem = self.items[path.row]
println("the selected item is \(selectedItem)")
}
Since you have 1 section in the table view you can get the cell object as below.
let indexPath = NSIndexPath(forRow: tag, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomCell!
where tag you will get from button tag.
Swift 3
I just get solution for access cell in #IBAction function using superview of button tag.
let cell = sender.superview?.superview as! ProductCell
var intQty = Int(cell.txtQty.text!);
intQty = intQty! + 1
let strQty = String(describing: intQty!);
cell.txtQty.text = strQty
#IBAction func buttonTap(sender: UIButton) {
let button = sender as UIButton
let indexPath = self.tableView.indexPathForRowAtPoint(sender.center)!
}
I updated option 1 of the answer from Vasil Garov for Swift 3
1. Create a protocol for your CustomCell:
protocol CustomCellDelegate {
func cellButtonTapped(cell: CustomCell)
}
2. For your TableViewCell declare a delegate variable and call the protocol method on it:
var delegate: CustomCellDelegate?
#IBAction func buttonTapped(sender: AnyObject) {
delegate?.cellButtonTapped(self)
}
3. Conform to the CustomCellDelegate in the class where your tableView is:
class ViewController: CustomCellDelegate
4. Set your cell's delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as CustomCell
cell.delegate = self
return cell
}
5. Implement the required method in your ViewController.
Based on Cao's answer, here is a solution to handle buttons in a collection view cell.
#IBAction func actionButton(sender: UIButton) {
let point = collectionView.convertPoint(sender.center, fromView: sender.superview)
let indexPath = collectionView.indexPathForItemAtPoint(point)
}
Be aware that the convertPoint() function call will translate the button point coordinates in the collection view space. Without, indexPath will always refer to the same cell number 0
XCODE 8: Important Note
Do not forget to set the tags to a different value than 0.
If you attempt to cast an object with tag = 0 it might work but in some weird cases it doesn't.
The fix is to set the tags to different values.
Hope it helps someone.