How to get the TextField position in a TableCell on iPhone?

一个人想着一个人 提交于 2019-12-04 13:23:06

you can make use of convetrPoint methods that can be used on an UIView or its derived classes

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view

in you case, you'll need to do this:

- (void)textFieldDidBeginEditing(UITextField *)textField 
{
     CGPoint textFieldOriginInTableView = [textFiled convertPoint:textField.frame.origin toView:tableView];
     //or if you want it relative to the orangeView, your toView should be the orangeView
}

There Are 2 thing I would like to mention:

  1. If your textField is inside tabelViewCell, it's position is always same, no matter how much cell goes up or down. It's because textField is subview of tabelViewCell not of view.

  2. You can get in several ways:

    • On textFieldDidBeginEditing delegate method (as you mentioned you need that when it is touched, means begin editing).

    • or when ever you want by following code:

    //you can set tag of text field

    UITableViewCell *cell = [yourTableView cellForrowAtIndexPath:yourCellIndexPath];
    UITextField *textField = (UITextField *)[cell.contentView viewWithTag:textFieldTag];
    

    //OR don't wanna set Tag and only textfield is there

    for (UIView *v in [cell.contentView subviews]) {
      if ([v isKindOfClass:[UITextField class]]) {
          UITextField *textField = (UITextField *)v;
     }
    }
    

Assuming that the owning view controller is the UITextField's delegate, you can implement the textFieldDidBeginEditing: method and get the frame of the text field like so:

- (void)textFieldDidBeginEditing(UITextField *)textField 
{
    CGRect rect = textField.frame;
}

First add a unique tag to the textField

yourTextField.tag = 1001;

Than at the point where you want the position of your textField, simply do

UITextField *myTextField = [cell viewWithTag:1001];

CGRect textFieldRect = myTextField.Frame;

It will give you the frame of your tagged textField containing x,y,width,height parameters of your textField with respect to its superView.

This code set frame with animation try this code...

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    CGRect youtTextFielfFrame = textField.frame;// get position of textfield from this code
    [textField setFrame:CGRectMake(textField.frame.origin.x - 50, textField.frame.origin.y,textField.frame.size.width,textField.frame.size.height)]; /// set frame which you want here......
    [UIView commitAnimations];
    return YES;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!