How to Detect Tableview Cell Touched or Clicked in Swift

How to detect tableView cell touched or clicked in swift

If you want the value from cell then you don't have to recreate cell in the didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println(tasks[indexPath.row])
}

Task would be as follows :

let tasks=["Short walk",
"Audiometry",
"Finger tapping",
"Reaction time",
"Spatial span memory"
]

also you have to check the cellForRowAtIndexPath you have to set identifier.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
var (testName) = tasks[indexPath.row]
cell.textLabel?.text=testName
return cell
}

Hope it helps.

Identify in which table view Cell button was pressed?

Use this line to get indexPath, Where you have to pass UIButton on target selector

func buttonTapped(_ sender:AnyObject) {
let buttonPosition:CGPoint = sender.convert(CGPointZero, to:self.tableView)
let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
}

Swift recognize tableView cell tap area

According to this thread, adding a Gesture recognizer can conflict with the TableView interactions.

Hence, To achieve what you require, you will have to add a gesture recognizer to the contentView of the UITableViewCell and get the tapped location of the gesture. For this,

  1. First, Define the UITapGestureRecognizer and the action within the UITableViewCell class. Refer the following code
    lazy var tap = UITapGestureRecognizer(target: self, action: #selector(didTapScreen))
.
.
.
// Gesture action
@objc func didTapScreen(touch: UITapGestureRecognizer) {
let xLoc = touch.location(in: self.contentView).x // Getting the location of tap
if xLoc > contentView.bounds.width/2 {
// RIGHT
} else {
// LEFT
}
}

  1. Add the following to the init() method of the custom cell as follows
    override init(frame: CGRect) {
super.init(frame: frame)
tap.numberOfTapsRequired = 1
contentView.addGestureRecognizer(tap)
// Other setups
}

I tried the code in a UICollectionViewCell and got the following output

Sample Image

Go to the ViewController by clicking on the TableView cell in swift

I assume you are using storyboards. First you need to set up some sort of connection between your two viewcontrollers. You can do this by setting up a "segue". You hold ctrl+click drag from the first viewcontroller to the 2nd viewcontroller. It looks like this:

Creating Segue

When you let go of the mouse, you will see this:

Creating Segue 2

Click on Show. Now you will have created a segue.
Now you need to name it. So click on the segue that shows up in the storyboard. It is basically just an arrow from the Menu View Controller to the Info View Controller. On the right hand side you will see a place where you can name it (give it an identifier):

Creating Segue 3

Now ... you have done all you needed to do in the storyboard. Now in your actual code in the MenuViewController, you need to associate clicking the tableviewcell. You do this by using the delegate method didSelectRowAt.

I see you have already set up the delegate with this line:
menuTableView.delegate = self

That ensures that didSelectRowAt will be called whenever the user taps on a row.

So now what you want to do is write the code to perform the segue:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "YourSegueName", sender: self)
}

Note:
Here is more information on interacting with a tableview row:
How to detect tableView cell touched or clicked in swift

Here is more information about segues:
IOS - How to segue programmatically using swift

There are many more customizations you can do ... such as passing data through to the next viewcontroller via the segues. Here's how:
Pass data through segue

How to detect double tap / touch event in tableview

There is a simple method, without using UITapGestureRecognizer nor implementing custom table view class.

@implementation MyTableViewController
NSTimeInterval lastClick;
NSIndexPath *lastIndexPath;

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSTimeInterval now = [[[NSDate alloc] init] timeIntervalSince1970];
if ((now - lastClick < 0.3) && [indexPath isEqual:lastIndexPath]) {
// Double tap here
NSLog(@"Double Tap!");
}
lastClick = now;
lastIndexPath = indexPath;
}
@end

It is just view lines of code.

Detect tap on a button in UITableViewCell for UITableView containing multiple sections

Objective-C

-(void)addItem:(UIButton*) sender
{

CGPoint touchPoint = [sender convertPoint:CGPointZero toView:mainTable]; // maintable --> replace your tableview name
NSIndexPath *clickedButtonIndexPath = [mainTable indexPathForRowAtPoint:touchPoint];

NSLog(@"index path.section ==%ld",(long)clickedButtonIndexPath.section);

NSLog(@"index path.row ==%ld",(long)clickedButtonIndexPath.row);

}

Swift3

 func addItem(sender: UIButton)
{
var touchPoint = sender.convert(CGPoint.zero, to: self.maintable)
// maintable --> replace your tableview name
var clickedButtonIndexPath = maintable.indexPathForRow(at: touchPoint)
NSLog("index path.section ==%ld", Int(clickedButtonIndexPath.section))
NSLog("index path.row ==%ld", Int(clickedButtonIndexPath.row))

}

Swift2 and above

func addItem(sender: UIButton)
{
var touchPoint: CGPoint = sender.convertPoint(CGPointZero, toView: mainTable)
// maintable --> replace your tableview name
var clickedButtonIndexPath: NSIndexPath = mainTable(forRowAtPoint: touchPoint)
NSLog("index path.section ==%ld", Int(clickedButtonIndexPath.section))
NSLog("index path.row ==%ld", Int(clickedButtonIndexPath.row))
}

how can I distinguish which part of UITableViewCell has been clicked

Rather than adding the gesture recognisers to each individual cell, you can add one to the table view and determine which cell was selected from the point of the users touch, and then determine if the user touched the image or the cell.

First make sure your controller adopts the UIGestureRecognizerDelegate protocol.

@interface MyTableViewController() <UIGestureRecognizerDelegate>
@end

Then add the UIGestureRecognizer to the UITableView when the view loads.

    - (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
singleTap.delegate = self;
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self.tableView addGestureRecognizer:singleTap];
}

This delegate method determines if the handleTap: method should be executed. If it can find an indexPath from the users touch, then it returns YES otherwise it returns NO.

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
UITableView *tableView = (UITableView *)gestureRecognizer.view;
CGPoint p = [gestureRecognizer locationInView:gestureRecognizer.view];
if ([tableView indexPathForRowAtPoint:p]) {
return YES;
}
return NO;
}

Once we have determined if the user has clicked in a cell, the handleTap: method is called, which then decides if the user touched the image, or any other part of the cell.

- (void)handleTap:(UITapGestureRecognizer *)tap
{
if (UIGestureRecognizerStateEnded == tap.state) {
UITableView *tableView = (UITableView *)tap.view;
CGPoint p = [tap locationInView:tap.view];
NSIndexPath* indexPath = [tableView indexPathForRowAtPoint:p];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
CGPoint pointInCell = [tap locationInView:cell];
if (CGRectContainsPoint(cell.imageView.frame, pointInCell)) {
// user tapped image
} else {
// user tapped cell
}
}
}

How to get the index of the row (cell) I clicked on in TableViewController]

override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
}


Related Topics



Leave a reply



Submit