Get indexPath of UICollectionView from UITable within - ios

I tried to implement a UITapGestureRecognizer to get the indexPath.row of the collectionView from a tableView.
I tried delegation too, but it doesn't seem to work.
protocol PassingCellDelegate {
func passingIndexPath(passing: KitchenVC)
}
class ViewController: UIViewController {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapSwitchTableViewCollection))
var delegate: PassingCellDelegate?
#IBAction func buttonCompletedTapped(sender: AnyObject) {
delegate?.passingIndexPath(passing: self)
}
func tapSwitchTableCollection(sender: UITapGestureRecognizer) {
if let cell = sender.view as? KitchenCollectionViewCell, let indexPath = collectionKitchen.indexPath(for: cell) {
if self.selectedIndexPaths == indexPath {
print("This in IF")
print(indexPath)
self.selectedIndexPaths = IndexPath()
} else {
print("This in ELSE")
print(indexPath)
self.selectedIndexPaths = indexPath
}
}
}
Cell class, where the tableView is contained in the CollectionViewCell
class CollectionCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource, PassingCellDelegate {
func passingIndexPath(passing: KitchenVC) {
passing.tapSwitchTableCollection(sender: passing.tap)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "OrdersCell")
if tableView == ordersTableView {
passingIndexPath(passing: KitchenVC())
}
}
I got the method for tapSwitchTableCollection from this post:
Click here!

I managed to get the right indexPath with this
protocol CustomCellDelegate { func passingIndexPath(passing: KitchenVC) }
class ViewController: UIViewController {
var delegate: PassingCellDelegate?
#IBAction func buttonCompletedTapped(sender: AnyObject) {
delegate?.passingIndexPath(passing: self)
}
func completedTapped(cell: KitchenCollectionViewCell) {
var thisIndex = collectionKitchen.indexPath(for: cell)
currentIndex = (thisIndex?[1])!
// This returns indexPath.row from the collectionView
}
}

Related

Change button title for selected row in TableView Swift

i have a view controller in which there is a tableview cell having button on it. Button with title add comments. when i click on add comments button then it take me to the next page where textfield is present when i write something in it then press done button then my button title for all the cell changes. But i want only selected row button title should change. Below is my code of table view.
class MyTabViewController: UIViewController {
var addCommentsValueStore: String = "Add Comments"
#IBOutlet weak var tabTableView : ContentWrappingTableView!
#IBAction func addCommentsAction(_ sender: UIButton) {
guard let nextVC = MyCommentsRouter.getMyCommentsViewScreen() else { return }
nextVC.passAddCommentsDelegate = self
self.navigationController?.pushViewController(nextVC, animated: true)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let indetifier = "MyTabTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: indetifier, for: indexPath) as! MyTabTableViewCell
cell.addCommentsButton.setTitle(addCommentsValueStore, for: UIControl.State.normal)
}
}
extension MyTabViewController: AddCommentsDelegate{
func passAddComments(instruction: String) {
addCommentsValueStore = instruction
print(addCommentsValueStore)
}
}
below is the code of next view controller:
import UIKit
protocol AddCommentsDelegate{
func passAddComments(instruction: String)
}
class MyCommentsViewController: UIViewController {
#IBOutlet var addCommentsTextField: UITextField!
var passAddCommentsDelegate: AddCommentsDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func backActionClick(_ sender: UIButton) {
// guard let nextVC = MyTabRouter.getMyTabViewScreen() else { return }
self.navigationController?.popViewController(animated: true)
}
#IBAction func DoneActionClick(_ sender: Any) {
let dataToBeSent = addCommentsTextField.text
self.passAddCommentsDelegate?.passAddComments(instruction: dataToBeSent!)
self.navigationController?.popViewController(animated: true)
}
}
You can do it in this delegate method as below:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (id object in cell.superview.subviews) {
if ([object isKindOfClass:[UITableViewCell class]]) {
UITableViewCell *cellNotSelected = (UITableViewCell*)object;
cellNotSelected.textLabel.textColor = [UIColor blackColor];
}
}
cell.textLabel.textColor = [UIColor redColor];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
you need to change you logic for done those things. First you need to declare string Wrong. Because string only hold a single value. You need to declare variable as Dictionary [IndexPath:String] Or AnyHashable Dictionary for store the value. I will give reference code below feel free to refer and if any doubt in the code please ask me in command
Reference Code
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var commend: [IndexPath: String] = [:]
}
extension FirstViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ListTableViewCell.self), for: indexPath) as! ListTableViewCell
cell.button.setTitle(commend[indexPath] ?? "Add commend", for: .normal)
cell.label.text = "\(indexPath.row)"
cell.button.addTarget(self, action: #selector(self.addCommentsAction(_:)), for: .touchUpInside)
return cell
}
#objc func addCommentsAction(_ sender: UIButton) {
guard let nextVC = UIStoryboard(name: "Main", bundle: .some(.main)).instantiateViewController(withIdentifier: String(describing: CommendViewController.self)) as? CommendViewController else { return }
let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
guard let indexPath = self.tableView.indexPathForRow(at: buttonPosition) else{
return
}
nextVC.delegate = self
nextVC.indexPath = indexPath
self.navigationController?.pushViewController(nextVC, animated: true)
}
}
extension FirstViewController: DataPassingDelegate{
func commendForIndex(_ string: String, indexPath: IndexPath) {
self.commend[indexPath] = string
self.tableView.reloadData()
}
}
class ListTableViewCell: UITableViewCell{
#IBOutlet weak var label: UILabel!
#IBOutlet weak var button: UIButton!
}
protocol DataPassingDelegate: AnyObject {
func commendForIndex(_ string: String, indexPath: IndexPath)
}
class CommendViewController: UIViewController {
#IBOutlet weak var textView: UITextView!
weak var delegate: DataPassingDelegate?
var indexPath = IndexPath()
#IBAction func doneCommend(_ sender: UIButton){
self.delegate?.commendForIndex(textView.text, indexPath: indexPath)
self.navigationController?.popViewController(animated: true)
}
}

How do I use tableView.indexPathForRow(at: touchPoint) with sections

I use sections to load messages(viewForFooterInSection) and rows to load the reply of specific messages if any.
Previously I was using a long press gesture on the tableView to detect a touch on the tableView and return the indexPath using tableView.indexPathForRow(at: touchPoint), however I have not found a similar method to get indexPath of long pressed cell
Can anyone help?
I am not sure why you are going for cell-level gesture when you have already achieved getting indexPath using gesture on tableview. In case you are trying to get cell from indexPath then you can try like
guard let cell = tableView.cellForRow(at: indexPath) else { return }
Anyhow coming to answer for your question, we can do the following way to get indexPath from cell-level.
protocol CustomCellDelegate: AnyObject {
func longPressAction(onCell: CustomCell)
}
class CustomCell: UITableViewCell {
weak var delegate: CustomCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
let lg = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
lg.minimumPressDuration = 0.5
lg.delaysTouchesBegan = true
self.addGestureRecognizer(lg)
}
#objc func longPress(gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizer.State.ended {
return
}
delegate?.longPressAction(onCell: self)
}
}
And in your tableview cell for row method, assign the delegate.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as? CustomCell else { return UITableViewCell() }
cell.delegate = self
return cell
}
And confirm to the CustomCellDelegate protocol in your viewController.
extension ViewController: CustomCellDelegate {
func longPressAction(onCell: CustomCell) {
guard let indexPath = tableView.indexPath(for: onCell) else { return }
print(indexPath.section, indexPath.row)
}
}

index of button in custom cell

I create a custom cell that contains a button, I need to create segue from this button to other VC but first of all, I would like to push an object with that segue.
I already try to use cell.button.tag, but I did not succeed.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMap" {
let mapVC = segue.destination as! MapViewController
//guard let indexPath = tableView.indexPathForSelectedRow else { return }
mapVC.place = places[] // <- "here I need index of button in cell"
}
}
Instead of using the segue, handle the navigation programatically through a closure in UITableViewCell.
class CustomCell: UITableViewCell {
var buttonTapHandler: (()->())?
#IBAction func onTapButton(_ sender: UIButton) {
self.buttonTapHandler?()
}
}
In the above code, I've create a buttonTapHandler - a closure, that will be called whenever the button inside the cell is tapped.
Now, in cellForRowAt method when you dequeue the cell, set the buttonTapHandler of CustomCell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.buttonTapHandler = {[weak self] in
if let mapVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MapViewController") as? MapViewController {
mapVC.place = places[indexPath.row]
self?.navigationController?.pushViewController(mapVC, animated: true)
}
}
return cell
}
In the above code, buttonTapHandler when called will push a new instance of MapViewController along with the relevant place based on the indexPath.
if you don't want to execute your code in didSelectRowAt method, another good approach in my opinion is to create a delegate of your custom cell. See the code below
// This is my custom cell class
class MyCustomCell: UITableViewCell {
// The button inside your cell
#IBOutlet weak var actionButton: UIButton!
var delegate: MyCustomCellDelegate?
#IBAction func myDelegateAction(_ sender: UIButton) {
delegate?.myCustomAction(sender: sender, index: sender.tag)
}
// Here you can set the tag value of the button to know
// which button was tapped
func configure(index: IndexPath){
actionButton.tag = index.row
}
}
protocol MyCustomCellDelegate {
func myDelegateAction(sender: UIButton, index: Int)
}
Delegate the ViewController where you use your custom cell.
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCellIdentifier", for: indexPath) as! MyCustomCell
cell.configure(index: indexPath)
cell.delegate = self
return cell
}
}
And at the end customize your method extending your custom cell delegate
extension MyViewController: MyCustomCellDelegate {
func myDelegateAction(sender: UIButton, index: Int) {
// Do your staff here
}
}
I hope I was helpful.
In the custom cell:
import UIKit
protocol CustomCellDelegate: class {
func btnPressed(of cell: CustomCell?)
}
class CustomCell: UITableViewCell {
weak var delegate: CustomCellDelegate?
#IBAction func btnTapped(_ sender: UIButton) {
delegate?.btnPressed(of: self)
}
}
And in the view controller:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCell(for: indexPath)
cell.delegate = self
return cell
}
extension ViewController: CustomCellDelegate {
func btnPressed(of cell: CustomCell?) {
if let cell = cell, let indexPath = tableView.indexPath(for: cell) {
// Your stuff here
}
}
}

Gather textfield text from a tableview cell (Swift)

I have a tableview with one textfield in each cell. I added a target like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customLevelCell") as! LevelTableViewCell
cell.cellTextField.addTarget(self, action: #selector(ViewController.TextfieldEditAction), for: .editingDidEnd)
return cell
}
But found out that I'm not able to use the indexpath.row / sender.tag to get the specific textfield text
#objc func TextfieldEditAction(sender: UIButton) {
}
So my question is how can I get the text after the user has edited one of the textfields.
Also how can i get the indexpath.row or sender.tag which will be used to collect the text they added to that specific textfield.
The easiest way to handle this is probably to use a delegate protocol…
In your cell
protocol LevelTableViewCellDelegate: class {
func levelTableViewCell(_ levelTableViewCell: LevelTableViewCell, didEndEditingWithText: String?)
}
class LevelTableViewCell: UITableViewCell {
#IBOutlet private weak var cellTextField: UITextField!
var delegate: LevelTableViewCellDelegate?
override func awakeFromNib() {
cellTextField.addTarget(self, action: #selector(didEndEditing(_:)), for: .editingDidEnd)
}
#objc func didEndEditing(_ sender: UITextField) {
delegate?.levelTableViewCell(self, didEndEditingWithText: sender.text)
}
}
In your view controller
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LevelTableViewCell") as! LevelTableViewCell
cell.delegate = self
return cell
}
}
extension TableViewController: LevelTableViewCellDelegate {
func levelTableViewCell(_ levelTableViewCell: LevelTableViewCell, didEndEditingWithText: String?) {
let indexPath = tableView.indexPath(for: levelTableViewCell)
// Now you have the cell, indexPath AND the string
}
Also, note that the view outlet is be private. You'll find that you write cleaner code if you follow this rule
Following is the extension of UIView that can be used to get the cell or indexPath of the cell enclosing textField
extension UIView {
var tableViewCell : UITableViewCell? {
var subviewClass = self
while !(subviewClass is UITableViewCell){
guard let view = subviewClass.superview else { return nil }
subviewClass = view
}
return subviewClass as? UITableViewCell
}
func tableViewIndexPath(_ tableView: UITableView) -> IndexPath? {
if let cell = self.tableViewCell {
return tableView.indexPath(for: cell)
}
return nil
}
}
Example :-
#objc func TextfieldEditAction(sender: UITextField) {
//replace tableView with the name of your tableView
guard let indexPath = sender.tableViewIndexPath(tableView) else {return}
}

How to delete a cell in tableView by clicking a button in a cell? Using coreData

I create a ToDo List app.
I used tableView to list the tasks. And I use a custom class for cell. In cell contentView I have a label and one done button in it. I have successfully implemented the done button click action in my code. It works fine.
Problem
When I click the done button it deletes the last added task. But not the clicked one. And when I retry to click the done Button it perform no action. How to resolve this error
GIF added below, click link
Entity class ToDo
import Foundation
import CoreData
public class ToDo: NSManagedObject {
public override func awakeFromInsert() {
self.created = NSDate()
}
}
MainVC
import UIKit
import CoreData
class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {
var controller: NSFetchedResultsController<ToDo>!
#IBOutlet weak var taskTextField: CustomTextField!
#IBOutlet weak var tableView: UITableView!
var toDo: ToDo!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// generateData()
attemptFetch()
}
// to give view to cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
configureCell(cell: cell, indexPath: indexPath as NSIndexPath)
return cell
}
// custom function
func configureCell(cell: ItemCell, indexPath: NSIndexPath) {
let toDo = controller.object(at: indexPath as IndexPath)
// call the method on the ItemCell
cell.configureCell(toDo: toDo)
// done button click
cell.doneBtn.tag = indexPath.row
cell.doneBtn.addTarget(self, action: #selector(MainVC.donePressed), for: UIControlEvents.touchUpInside)
}
// when select a cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// it ensure it have object and atleast one object in there
if let objs = controller.fetchedObjects, objs.count > 0 {
let task = objs[indexPath.row]
performSegue(withIdentifier: "ItemDetailsVC", sender: task)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ItemDetailsVC" {
if let destination = segue.destination as? ItemDetailsVC {
if let task = sender as? ToDo {
destination.taskDetails = task
}
}
}
}
// count of cells
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// we check here if any sections then take info of them and count
if let sections = controller.sections {
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
return 0
}
// column count
func numberOfSections(in tableView: UITableView) -> Int {
if let sections = controller.sections {
return sections.count
}
return 0
}
// give height of a cell
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
// fetching function
func attemptFetch() {
// create a fetch request with fetching Entity
let fetchRequest: NSFetchRequest<ToDo> = ToDo.fetchRequest()
// sorting area
let dateSort = NSSortDescriptor(key: "created", ascending: true)
fetchRequest.sortDescriptors = [dateSort]
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = self
self.controller = controller
// actual fetching
do {
try controller.performFetch()
} catch {
let error = error as NSError
print("\(error)")
}
}
// when tableView changes this function starts listen for changes and
// it will handle that for you
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
// this function will listen for when we make change
// insertion, deletion .. etc
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case.insert:
if let indexPath = newIndexPath {
tableView.insertRows(at: [indexPath], with: .fade)
}
break
case.delete:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
break
case.update:
if let indexPath = indexPath {
let cell = tableView.cellForRow(at: indexPath)
//update the cell data
configureCell(cell: cell as! ItemCell, indexPath: indexPath as NSIndexPath)
}
break
case.move:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
if let indexPath = newIndexPath {
tableView.insertRows(at: [indexPath], with: .fade)
}
break
}
}
#IBAction func addBtnPressed(_ sender: UIButton) {
if taskTextField.text != "" && taskTextField.text != nil {
toDo = ToDo(context: context)
if let task = taskTextField.text {
toDo.title = task
}
ad.saveContext()
taskTextField.text = ""
self.tableView.reloadData()
}
}
// done button
func donePressed() {
if toDo != nil {
context.delete(toDo)
ad.saveContext()
}
}
func generateData() {
let task = ToDo(context: context)
task.title = "alwin"
let task1 = ToDo(context: context)
task1.title = "rambo"
let task2 = ToDo(context: context)
task2.title = "monisha"
let task3 = ToDo(context: context)
task3.title = "wounderlist"
let task4 = ToDo(context: context)
task4.title = "presentation"
let task5 = ToDo(context: context)
task5.title = "roundup"
// to save data
ad.saveContext()
}
}
ItemDetailsVC
import UIKit
class ItemDetailsVC: UIViewController {
var taskDetails: ToDo?
#IBOutlet weak var detailsLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// to clear the <DreamLIst to < only
if let topItem = self.navigationController?.navigationBar.topItem {
topItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
// this is execute when tap on an existing cell
if taskDetails != nil {
loadItemData()
}
}
}
func loadItemData() {
if let task = taskDetails {
detailsLbl.text = task.title
}
}
override func viewDidLayoutSubviews() {
detailsLbl.sizeToFit()
}
#IBAction func deletePressed(_ sender: UIBarButtonItem) {
if taskDetails != nil {
context.delete(taskDetails!)
ad.saveContext()
}
_ = navigationController?.popViewController(animated: true)
}
}
storyboard, click link below
ItemCell
import UIKit
class ItemCell: UITableViewCell {
#IBOutlet weak var taskTitle: UILabel!
#IBOutlet weak var doneBtn: UIButton!
var toDo: ToDo?
func configureCell(toDo: ToDo) {
taskTitle.text = toDo.title
}
}
OK Currently you are setting the selector of your done button to outside of its container (cell) this is bad practice in general, you are configuring the cell with a ToDo but not assigning the optional inside the cell, supposedly there to keep a reference to the ToDo.
In my opinion I would change this slightly so that you store the reference to the ToDo firstly:
func configureCell(toDo: ToDo) {
self.toDo = toDo
taskTitle.text = toDo.title
}
Now on your cell create a Protocol, then configure the cell with a ToDo and a delegate, then on button press tell the delegate your button was pressed with the relevant ToDo...
protocol ToDoCellDelegate: class {
func toDoCellButtonPressed(todo: ToDo?)
}
Now on your cell configure as:
func configureCell(toDo: ToDo, delegate: ToDoCellDelegate) {
self.delegate = delegate
self.toDo = toDo
taskTitle.text = toDo.title
}
and add a ref to the delegate in the cell:
weak var delegate: ToDoCellDelegate?
now change your buttons selector to a func inside the cell
func buttonPressed() {
self.delegate?.cellToDoButtonPressed(toDo: toDo)
}
Then in your VC you conform to the delegate passing self in the configuration and implement the delegate:
extension ItemDetailsVC: ToDoCellDelegate {
func toDoCellButtonPress(toDo: ToDo?) {
if let t = toDo {
//tell context to delete todo and remove cell.
}
}
}
Ok so then you should create an IBAction outlet for your button in ItemCell and then create a protocol of this form :
protocol ItemDelegate {
func clicked()
}
class ItemCell: UITableViewViewCell {
var delegate : ItemDelegate?
var indexPath: IndexPath?
//call delegate?.clicked() where you have the gesture recogniser
}
Then in cellForRowAtIndexPath
cell.delegate = self
cell.indexPath = indexPath
Then implement the extension for your class:
extension MyTableView: ItemDelegate {
func clicked(indexPath: IndexPath) {
//dismiss cell for indexPath
}
}

Resources