UIButton inside table not triggering - ios

Hello I'm trying to figure out how to call a UIButton inside a custom cell within a UItable in storyboard. At the moment I have a library that creates a sidemenu working just fine (more info here) and I can see the button I placed when I launch the simulator. However, when I click on the button the action is not triggered, can you please guide me as to how I can achieve this?
Important to note that the table was create entirely in storyboard.
My work in progress code within TopratedVC.swift to get the button to trigger the action:
override func viewDidLoad() {
super.viewDidLoad()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewVibrantCell") as! CellClassMenu
cell.sendFeedBackBtn.tag = indexPath.row
cell.sendFeedBackBtn.addTarget(self, action: "sendFeedBackBtnAction:", forControlEvents: .TouchUpInside)
cell.contentView.userInteractionEnabled = false //tried with true as well, no difference
cell.bringSubviewToFront(cell.sendFeedBackBtn)
cell.userInteractionEnabled = true
return cell
}
func sendFeedBackBtnAction(sender: UIButton){
print("sendFeedBackBtnAction tapped")
}
My UITableViewVibrantCell.swift file contains the following:
import UIKit
class UITableViewVibrantCell: UITableViewCell {
#IBOutlet var sendFeedBackBtn: UIButton!
}
My sndFeedBackBtn has a referencing outlet to UITableViewVibrantCellsendFeedBackBtn which has a class of UITableViewVibrantCell. What am I doing wrong? Thank you.
What it looks like in simulator:

In your post, you show a UITableViewVibrantCell class, and dequeue a cell with the "UITableViewVibrantCell" identifier, but cast it as CellClassMenu?
Anyhow, it would be better practice to create a cell delegate for actions, and let your controller decide the implementation, rather than adding a target every time the cell is dequeued. You can do that like so:
UITableViewVibrantCell
import UIKit
protocol UITableViewVibrantCellDelegate: NSObjectProtocol {
func buttonPressed(sender: UIButton)
}
class UITableViewVibrantCell: UITableViewCell {
var delegate: UITableViewVibrantCellDelegate?
#IBOutlet var feedbackButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
feedBackButton.addTarget(self, action: #selector(self.buttonPressed(_:)), forControlEvents: .TouchUpInside)
}
func buttonPressed(sender: UIButton) {
delegate?.buttonPressed(sender)
}
}
TopratedVC
class TopratedVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewVibrantCell") as! UITableViewVibrantCell
cell.delegate = self
return cell
}
// MARK: - UITableViewVibrantCellDelegate
func buttonPressed(sender: UIButton) {
print("feedbackButton tapped")
}
}

Selectors ("sendFeedBackBtnAction:") can't pass parameters. And a param isn't needed in the sendFeedBackBtnAction function since you're calling it only for this button. So change I'd change it to simply...
func sendFeedBackBtnAction()
then I'd also recommend changing your selector to a more updated swift version...
cell.sendFeedBackBtn.addTarget(self, action: #selector(sendFeedBackBtnAction), forControlEvents: .TouchUpInside)

Related

How to identify click from multiple buttons in a UITableViewCell from a UITableView - Swift 4

I want to implement UITableView Where I want to have 3 buttons in each UITableViewCell. I want to perform a diffeent action for each button. How can I identify which button is bring pressed and then get the object(index row ) of the cell that was selected?
UIViewController
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let show=shows[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ShowCell") as!
ShowCell
cell.setShow(show: show)
return cell
}
UITableViewCell
#IBOutlet weak var graphButton: FlatButton!
#IBOutlet weak var buyButton: FlatButton!
#IBOutlet weak var reviewButton: FlatButton!
func setShow(show :StubHubEvent ){
let url = URL(string: show.imageurl)!
showImageView.af_setImage(withURL: url)
showImageView.contentMode = .scaleAspectFill
showImageView.clipsToBounds = true
nameLabel.text = show.title
dateLabel.text = show.time
implement your button action in UIviewcontroller not a UITableViewCell, create the target in inside the cellforRow as well as add the Tag for each target for identify which button was user pressed.for E.g
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let show=shows[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ShowCell") as!
ShowCell
cell.graphButton.tag = indexPath.row
cell.buyButton.tag = indexPath.row
cell.reviewButton.tag = indexPath.row
cell.graphButton?.addTarget(self, action: #selector(self.graphButtonClicked(_:)), for: .touchUpInside)
cell.buyButton?.addTarget(self, action: #selector(self.buyButtonClicked(_:)), for: .touchUpInside)
cell.reviewButton?.addTarget(self, action: #selector(self.reviewButtonClicked(_:)), for: .touchUpInside)
cell.setShow(show: show)
return cell
}
and handle the action as like
#objc func buyButton( _ sender: UIButton) {
print("buyButton Action Found the index of \(sender.tag)")
}
#objc func graphButtonClicked( _ sender: UIButton) {
print("graphButtonClicked Action Found the index of \(sender.tag)")
}
#objc func reviewButtonClicked( _ sender: UIButton) {
print("reviewButtonClicked Action Found the index of \(sender.tag)")
}
Option 2
if you want to perform in your button action in UItableviewcell class using delegate pattern, then refer this duplicate answer
there are two ways to get button click execution in the ViewController from TableViewCell
Use Delegate pattern
Use blocks as callbacks and handle block execution in the cellForRow method
Add addTarget(:) to add a target method for the button click
Details:
The first approach is best among all the three mentioned approaches, in this, you need to create a delegate which redirects your user actions from cell to view controller. Check below code example.
The second approach is similar to the first one, it just redirects the same method calls using the blocks instead of Delegate methods and protocol.
The third approach is not good, as it is tightly coupled with the indexPath.row value, in the software development industry
Cohesion should be high, Coupling should be low.
Code of first Approach:
//MARK:- Model - StubHubEvent
class StubHubEvent {
//you model class implementation
}
//MARK:- Protocol - ShowCellUIInteractionDelegate - used to redirect user actions from cell to viewController
protocol ShowCellUIInteractionDelegate: AnyObject {
func showCell(cell: ShowCell, didTapBuyFor show: StubHubEvent)
func showCell(cell: ShowCell, didTapGraphFor show: StubHubEvent)
func showCell(cell: ShowCell, didTapReviewFor show: StubHubEvent)
}
//MARK:- Cell- ShowCell
class ShowCell: UITableViewCell {
var show: StubHubEvent!
weak var delegateUIInteraction: ShowCellUIInteractionDelegate?
func setShow(show :StubHubEvent ){
self.show = show
//your other setup
}
//Bind these three action from cell to buttons as a .touchUpInside event
#IBAction func buttonBuyDidTap( _ sender: UIButton) {
self.delegateUIInteraction?.showCell(cell: self, didTapBuyFor: self.show)
}
#IBAction func buttonGraphDidTap( _ sender: UIButton) {
self.delegateUIInteraction?.showCell(cell: self, didTapGraphFor: self.show)
}
#IBAction func buttonReviewDidTap( _ sender: UIButton) {
self.delegateUIInteraction?.showCell(cell: self, didTapReviewFor: self.show)
}
}
//MARK:- ViewController - ShowListingViewController
class ShowListingViewController: UIViewController {
//you ShowListingViewController implementation
}
//MARK:- Extension - ShowCellUIInteractionDelegate
extension ShowListingViewController: ShowCellUIInteractionDelegate {
//execute your logic for the show model object
func showCell(cell: ShowCell, didTapBuyFor show: StubHubEvent){
}
func showCell(cell: ShowCell, didTapGraphFor show: StubHubEvent){
}
func showCell(cell: ShowCell, didTapReviewFor show: StubHubEvent){
}
}

Swift 4.2: Unable to add custom behaviour to a custom UITableViewCell using Protocol oriented delegate concepts

I've a custom UITableViewCell, in that I've two UILabels & one UIButton. I'm able to load data...and display it as per requirement.
Problem Statement-1: Now problem exist in my UIButton, which is in my UICustomTableViewCell. Due to this I'm unable to handle click event on that UIButton.
Problem Statement-2: On button Click I have to identify the index of that Button click and pass data to next ViewController using segue.
Now have a look on...what did I've tried for this...
Yes, first-of-all I have thought that Binding IBOutlet action in my CustomCell will resolve my problem...but actually it doesn't solved my problem.
After that I've accessed button using .tag and initialised index path.row to it.
But it won't helped me.
So now I'm using Protocol oriented concept using delegate to handle click event on my UIButton which is available in CustomCell.
What did I tried:
SwiftyTableViewCellDelegate:
protocol SwiftyTableViewCellDelegate : class {
func btnAuditTrailDidTapButton(_ sender: LeadCustomTableViewCell)
}
CustomTableViewCell with delegate:
class LeadCustomTableViewCell: UITableViewCell {
#IBOutlet weak var lblMeetingPersonName: UILabel!
#IBOutlet weak var lblPolicyNo: UILabel!
#IBOutlet weak var btnLeadAuditTrail: UIButton!
weak var delegate: SwiftyTableViewCellDelegate?
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func btnAuditTrailTapped(_ sender: UIButton) {
delegate?.btnAuditTrailDidTapButton(self)
}
}
ViewController implementing delegate:
class LeadViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SwiftyTableViewCellDelegate {
//IBOutlet Connections - for UITableView
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//setting dataSource & delegates of UITableView with this ViewController
self.tableView.dataSource = self
self.tableView.delegate = self
//Reloading tableview with updated data
self.tableView.reloadData()
//Removing extra empty cells from UITableView
self.tableView.tableFooterView = UIView()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:LeadCustomTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! LeadCustomTableViewCell
//Assigning respective array to its associated label
cell.lblMeetingPersonName.text = (meetingPersonNameArray[indexPath.section] )
cell.lblPolicyNo.text = (String(policyNoArray[indexPath.section]))
cell.btnLeadAuditTrail.tag = indexPath.section
cell.delegate = self
return cell
}
//This is delegate function to handle buttonClick event
func btnAuditTrailDidTapButton(_ sender: LeadCustomTableViewCell) {
guard let tappedIndexPath = tableView.indexPath(for: sender) else { return }
print("AuditTrailButtonClick", sender, tappedIndexPath)
}
Don't know why this is not working.
Link the touch up inside event in cellForRow by adding the following code:
cell.btnLeadAuditTrail.addTarget(self, action:#selector(btnAuditTrailDidTapButton(_:)), for: .touchUpInside)

How to perform action for a custom UITableViewCell inside my viewController?

I have a custom cell that has a xib, this cell contains a button, when the button is pressed I want to do an action , but not inside my custom cell class but from inside the viewcontroller that contains the tableview of the custom cell, any help please?
First of all you should write a protocol for example:
protocol CustomCellDelegate {
func doAnyAction(cell:CustomUITableViewCell)
}
Then inside your custom cell class declare:
weak var delegate:CustomCellDelegate?
and inside your IBAction in the custom cell class:
#IBAction func onButtonTapped(_ sender: UIButton) {
delegate?.doAnyAction(cell: self)
//here we say that the responsible class for this action is the one that implements this delegate and we pass the custom cell to it.
}
Now in your viewController:
1- Make your view controller implement CustomCellDelegate.
2- In your cellForRow when declaring the cell don't forget to write:
cell.delegate = self
3- Finally call the function in your viewcontroller:
func doAnyAction(cell: CustomUITableViewCell) {
let row = cell.indexPath(for: cell)?.row
//do whatever you want
}
}
You can use delegate pattern. Create a custom protocol.
protocol CustomTableViewCellDelegate {
func buttonTapped() }
and on tableview cell conform delegate
class CustomTableViewCell: UITableViewCell {
var delegate: CustomTableViewCellDelegate!
#IBAction func buttonTapped(_ sender: UIButton) {
delegate.buttonTapped()
} }
table view data source
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! CustomTableViewCell
cell.delegate = self
return cell
}
conform protocol(delegate) from table view controller or view controller
extension TestViewController: CustomTableViewCellDelegate {
func buttonTapped() {
print("do something...")
} }
Just get the UIButton in your cellForRowAtIndexpath.
Then write the following code.
button.addTarget(self, action:#selector(buttonAction(_:)), for: .touchUpInside).
func buttonAction(sender: UIButton){
//...
}
Add action for button from tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) method from your viewController.
cell.btn.tag = indexPath.row;
cell.btn.addTarget(self, action:#selector(handleButtonClicked(_:)), for: .touchUpInside).
Write selector function in your view Controller:
func handleButtonClicked(sender: UIButton){
int cellofClickedbutton = sender.tag;
//...
}
In your cell define a protocol:
protocol MyCellDelegate: class {
func buttonTapped()
}
and define a delegate variable:
weak var delegate: MyCellDelegate?
Make your viewController conform to the defined protocol.
When creating the cell in the viewController, assign it the delegate:
cell.delegate = self
When the button in the cell is tapped, send the delegate appropriate message:
delegate?.buttonTapped()
In your viewController implement the method:
func buttonTapped() {
//do whatever you need
}
You can pass as an argument the cell's index, so the viewController knows which cell button was tapped.

UITableViewCell Button is not Clickable IOS Swift

So basically I am trying to do this:
I have a TableView that I load a custom cell (xib) into it. This custom cell has its own corresponding custom class to go with it. The cell loads just fine but the button is not clickable (at all, as in you don't even see any type of indication that the button was clicked at all). I did some googling, tried to set the action in the cell, tried using a delegate to handle the action. I am lost.
Here is the code from the files:
ViewController.swift
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Use your cell's reuse identifier and cast the result
// to your custom table cell class.
let cell = tableView.dequeueReusableCellWithIdentifier("ReserveTableViewCell", forIndexPath: indexPath) as! ReserveTableViewCell
cell.delegate = self
let button = cell.locationButton.viewWithTag(1) as? UIButton
button?.addTarget(self, action: #selector(ReserveTableViewController.loc(_:)), forControlEvents: .TouchUpInside)
cell.pickupDate.text = "Today"
cell.returnDate.text = "Tomorrow"
//cell.locationButton.addTarget(self, action: #selector(loc), forControlEvents: .TouchUpInside)
return cell
}
func loc(sender: UIButton!) {
print("here")
}
CustomCell.swift
import UIKit
protocol ReserveTableViewCellDelegate {
func pickupLocationClick(cell: ReserveTableViewCell)
}
class ReserveTableViewCell : UITableViewCell {
#IBOutlet weak var searchButton: UIButton!
#IBOutlet weak var compactIcon: UIImageView!
#IBOutlet weak var midsizeIcon: UIImageView!
#IBOutlet weak var suvIcon: UIImageView!
#IBOutlet weak var luxuryIcon: UIImageView!
#IBOutlet weak var sportIcon: UIImageView!
#IBOutlet weak var pickupIcon: UIImageView!
#IBOutlet weak var pickupDate: UILabel!
#IBOutlet weak var returnDate: UILabel!
#IBOutlet weak var locationButton: UIButton!
var delegate: ReserveTableViewCellDelegate?
#IBAction func locationButtonAction(sender: AnyObject) {
delegate?.pickupLocationClick(self)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Some code is still left from other attempts (which is why the protocol method doesn't match the "loc" that is now defined in the viewcontroller.swift file.
In my TableView in storyboard I have selection turned off, when it is on and you tab on the cell it makes it all look "dim" so to speak.
I have the custom class set in my tableview and the outlets/actions are link in IB.
Anyone?
In my experience, it is possible to add functionality to the button in both the Cell file and in the ViewController file (which holds your TableView as a member)
ViewController.swift
#IBAction func locationButtonAction(sender: AnyObject) {
// Do Some Action Here (Which interacts with data members of View
}
CustomCell.swift
#IBAction func locationButtonAction(sender: AnyObject) {
// Do Another Action (Which interacts with data members of the cell)
}
Both of these functions can be linked to the TouchUpInside of the Cell button using the Storyboard Editor!
Best of luck!
Couple confusing things here...
let button = cell.locationButton.viewWithTag(1) as? UIButton
This means, hey locationButton, look in your subviews to find viewWithTag of 1. Not what you want. Just use
let button = cell.locationButton
Then you need to decide what action you're calling and what class does it live in. If you want the button to call an action in the ViewController class you add a target like:
button.addTarget(self, action: #selector(ViewController.loc(_:)), forControlEvents: .TouchUpInside)
If you want the button to call an action inside the ReserveTableViewController class, which honestly is pretty odd, you need a way to reference that class
button.addTarget(myReferenceToTheReserveTableViewControllerClass, action: #selector(ReserveTableViewController.loc(_:)), forControlEvents: .TouchUpInside)
What you may be actually looking for is for the button to call a method inside the cell class, in which you can then respond as necessary or delegate out to another class, which would then be:
button.addTarget(cell, action: #selector(ReserveTableViewCell.loc(_:)), forControlEvents: .TouchUpInside)
I have set up project just like you did. One thing i noticed in your in ViewController.swift is that you have written following code.
let button = cell.locationButton.viewWithTag(1) as? UIButton //If you will print or debug this button you will see nil
print("Button: \(button)") //prints "Button: nil"
button?.addTarget(self, action: #selector(ReserveTableViewController.loc(_:)), forControlEvents: .TouchUpInside)
Above code is not adding target for your Button. It is adding target for your Buttons subview which has tag value 1. Which is actually nil. Try following code.
cell.locationButton.addTarget(self, action: #selector(ReserveTableViewController.loc(_:)), forControlEvents: .TouchUpInside)(self, action: #selector(clicked), forControlEvents: .TouchUpInside)
Try the following code in your ViewController.swift
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Use your cell's reuse identifier and cast the result
// to your custom table cell class.
let cell = tableView.dequeueReusableCellWithIdentifier("ReserveTableViewCell", forIndexPath: indexPath) as! ReserveTableViewCell
cell.delegate = self
//let button = cell.locationButton.viewWithTag(1) as? UIButton
//button?.addTarget(self, action: #selector(ReserveTableViewController.loc(_:)), forControlEvents: .TouchUpInside)
cell.locationButton.addTarget(self, action: #selector(loc), forControlEvents: .TouchUpInside)
cell.pickupDate.text = "Today"
cell.returnDate.text = "Tomorrow"
return cell
}
func loc(sender: UIButton!) {
print("here")
}

How to add gesture to UITableViewCell?

I want to add a tap gesture to every cell in a UITableView that edits the content in it. The two ways to add a gesture are in code or through storyboard. I tried both and they failed.
Can I add a gesture to every cell in table with storyboard drag and drop? It seems to only add gesture to the first cell. Adding gesture in code, I wrote something like,
addGestureRecognizer(UITapGestureRecognizer(target: self,action:#selector(MyTableViewCell.tapEdit(_:))))
or
addGestureRecognizer(UITapGestureRecognizer(target: self, action:"tapEdit:"))
both work. But I'd like to let the UITableViewController handle this gesture because it does something with the datasource. How do I write my target and action?
EDIT:
addGestureRecognizer(UITapGestureRecognizer(target: MasterTableViewController.self, action:#selector(MasterTableViewController.newTapEdit(_:)))
it induce an error said, unrecognized selector sent to class 0x106e674e0...
To add gesture to UITableViewCell, you can follow the steps below:
First, add gesture recognizer to UITableView
tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewController.tapEdit(_:)))
tableView.addGestureRecognizer(tapGesture!)
tapGesture!.delegate = self
Then, define the selector. Use recognizer.locationInView to locate the cell you tap in tableView. And you can access the data in your dataSource by tapIndexPath, which is the indexPath of the cell the user tapped.
func tapEdit(recognizer: UITapGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Ended {
let tapLocation = recognizer.locationInView(self.tableView)
if let tapIndexPath = self.tableView.indexPathForRowAtPoint(tapLocation) {
if let tappedCell = self.tableView.cellForRowAtIndexPath(tapIndexPath) as? MyTableViewCell {
//do what you want to cell here
}
}
}
}
It is possible to add gesture directly to TableView cell and access the datasource in viewController, You need to set up a delegate:
In your custom cell:
import UIKit
class MyTableViewCell: UITableViewCell {
var delegate: myTableDelegate?
override func awakeFromNib() {
super.awakeFromNib()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MyTableViewCell.tapEdit(_:)))
addGestureRecognizer(tapGesture)
//tapGesture.delegate = ViewController()
}
func tapEdit(sender: UITapGestureRecognizer) {
delegate?.myTableDelegate()
}
}
protocol myTableDelegate {
func myTableDelegate()
}
In your viewController:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, myTableDelegate {
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 35
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? MyTableViewCell
cell?.delegate = self
return cell!
}
func myTableDelegate() {
print("tapped")
//modify your datasource here
}
}
However, this method could cause problems, see UIGestureRecognizer and UITableViewCell issue. In this case, when the swipe gesture successes, the selector get called twice for some reason. I can't say the second method is a bad one as I haven't found any direct evidence yet, but after searching through Google, it seems like the first method is the standard way.
You don't need to add gesture recognizer to achieve what you are doing.
Use the UITableViewDelegate method tableView:didSelectRowAtIndexPath: to detect which row is tapped (this is what exactly your tapGesture is going to do) and then do your desired processing.
If you don't like the gray indication when you select cell, type this in your tableView:didEndDisplayingCell:forRowAtIndexPath: just before returning the cell:
cell?.selectionStyle = .None
Adding gesture in awakeFromNib method seems much more easier and works fine.
class TestCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
let panGesture = UIPanGestureRecognizer(target: self,
action: #selector(gestureAction))
addGestureRecognizer(panGesture)
}
#objc func gestureAction() {
print("gesture action")
}
}
The easiest way to do this is to add the gesture in a custom UITableViewCell. An easier alternative to setting up a custom delegate pattern is to inform the view controller of the edits would be to use a handler in the form of a closure that the view controller can provide and which is called when user editing is finished. I'm assuming a textField is used to allow cell editing.
class CustomTableViewCell: UITableViewCell {
func activateTitleEditing() {
textField.isEnabled = true
textField.becomeFirstResponder()
}
// This will hold the handler closure which the view controller provides
var resignationHandler: (() -> Void)?
#objc private func tap(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
activateTitleEditing()
}
#IBOutlet weak var textField: UITextField! { didSet {
textField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
addGestureRecognizer(tap)
textField.isEnabled = false
}}
}
extension CustomTableViewCell: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
resignationHandler?()
}
}
And within your custom UITableViewController, pass in the handler to be able to make changes to your model. Don't forget to account for possible memory cycles in the closure.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// initialize and return table view cell
let cell = tableView.dequeueReusableCell(withIdentifier: K.documentCellIdentifier, for: indexPath)
assert(cell is CustomTableViewCell, "Document cell dequeuing error")
let customCell = cell as! DocumentTableViewCell
customCell.textField.text = documentModel.documents[indexPath.row]
customCell.resignationHandler = { [weak self, unowned customCell] in
guard let self = self else { return }
if let newTitle = customCell.textField.text {
self.cellModel.cells[indexPath.row] = newTitle
}
}
return customCell
}

Resources