ChrisTauziet
ChrisTauziet

Reputation: 179

Get the position of an element

I'm having trouble trying to scroll up a tableView when the user start editing a UITextField displayed in one of the cells.

My problem is that I can't find a way to know the position of the UITextField in the view. If I try to do activeTextField.frame.origin.y, I get the position of the TextField inside the cell, but not inside the tableView.

The way I build the view is the following : I've got a TableViewController, which creates cells using a custom class that initializes the UITextField. Then my TableViewController set the UITextField delegate to itself, so I can trigger the textFieldDidBeginEditing event. But if I try to NSLog the y origin of the TextField, I always get the same value for each UITextField, which is its position in the cell.

Any idea on how I can solve this?

Upvotes: 2

Views: 4510

Answers (5)

TheEye
TheEye

Reputation: 9346

It's always confusing with these coordinate system changes ...

This should work to get you the point in the table view coordinate system:

CGPoint textFieldCenter = textField.center;
CGPoint pointInTableView = [tableView convertPoint:textFieldCenter fromView:textField.superview];

If you want to have it in a different view, you should replace tableView with the view you want to have the coordinate in.

And if you want to get the cell in the table the textField was in:

NSIndexPath* path = [tableView indexPathForRowAtPoint:pointInTableView];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:path];

Upvotes: 6

Bonnie
Bonnie

Reputation: 4953

this should help you out This is simple and easy way of doing what you want

Upvotes: 1

hchouhan02
hchouhan02

Reputation: 946

try this

CGPoint locationinView=[cellView convertPoint:location fromView:tableView];

here location is the point of textField in cellView.

Upvotes: 0

vdaubry
vdaubry

Reputation: 11439

To get the position of your textfield should use the UIView method convertRect:toView:

convertRect:toView: Converts a rectangle from the receiver’s coordinate system to that of another view.

  • (CGRect)convertRect:(CGRect)rect toView:(UIView *)view

example :

CGRect textFieldFrame = [self.tableview convertRect:yourTextField.frame toView:self.view];

Upvotes: 2

Ganzolo
Ganzolo

Reputation: 1394

Yes, try using this method :

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated

When you prompt the keyboard, scroll the tableView to the selected cell it should bring the cell to the top of the screen.

Upvotes: 0

Related Questions