用户在屏幕上敲击屏幕上的任何地方创建一个UITEXTFIELD



我正在制作一个iPad应用程序,该应用程序将能够识别用户在视图中点击的位置并在该位置创建UITEXTFIELD。编程的最有效方法是什么?它适用于多个文本字段吗?

我认为您的想法听起来有些奇怪,但您可能想使用UITapGestureRecognizer。代码看起来像这样:

// In viewDidLoad
UITapGestureRecognizer *tapRecognizer = [UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedInView:)];
[self.view addGestureRecognizer:tapRecognizer];

- (void)tappedInView:(UIGestureRecognizer *)gestureRecognizer
{
     CGPoint pointForTextField = [gestureRecognizer locationInView:gestureRecognizer.view];
     // Add the UITextField to your view. You could use the pointForTextField as either the origin or center of the text field
    UITextField *textField = [UITextField alloc] initWithFrame:CGRectMake(pointForTextField.x,pointForTextField.y,100,44)];
    [self.view addSubview:textField];
}
//text field move where you touch in screen
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
    point = [myTouch locationInView:self.view];
    NSLog(@"%f,%f",point.x, point.y);
    yourTextField.frame = CGRectMake(point.x, point.y, width,height);
}

执行此操作:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   CGPoint locationPoint = [[touches anyObject] locationInView:self.view];
   if(locationPoint)
   {
     //add UITextField
     yourTextField.frame = CGRectMake(locationPoint.x, locationPoint.y, 40,40); //change height and width according
   }
}

最新更新