Here is the UI...(I know it is ugly...) The orange is a view, and the blue is the table, and the gray one is the table cell, lastly, the red is a textfield in a table cell. My question is simple, I just wanna to know the red text field position... Seems the table cell may move up and down, so, the position can be changed. So, I don't need to dynamic update the text field position, I just need the position when the user click the text field, any ideas? Thanks.
问题:
回答1:
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
}
回答2:
There Are 2 thing I would like to mention:
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.
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; } }
回答3:
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;
}
回答4:
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.
回答5:
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;
}