使用UITapGestureRecognizer根据iPhone中的手指触摸位置添加新视图

时间:2013-04-26 11:32:46

标签: iphone ios objective-c ipad ios6

对所有人 我正在使用

 UITapGestureRecognizer*singleTap = [[[UITapGestureRecognizer alloc] initWithTarget: self action:@selector(doSingleTap:)] autorelease];
    singleTap.numberOfTouchesRequired = 2;
    [self.view addGestureRecognizer:singleTap

获取触摸

在doSingleTap:方法我有这个

-(void)doSingleTap:(UITapGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer locationOfTouch:0 inView:self.view];
    NSLog(@"location X =>%f,location  =>%f ",point.x,point.y);
    CGPoint point1 = [recognizer locationOfTouch:1 inView:self.view];
    NSLog(@"location X =>%f,location  =>%f ",point1.x,point1.y);

     NSLog(@"location X =>%f,location  =>%f ",x,y);
    UIView *test1 = [[UIView alloc]initWithFrame:CGRectMake(point.x, point1.y, x, y)];
    test1.backgroundColor= [UIColor greenColor];
    [self.view addSubview:test1];


}

根据手指位置或位置在主视图上添加新视图时出现问题View正在根据位置正确添加视图。

我希望该视图根据两个手指添加并自动调整它们(x,y,w,h)。 如果有人帮助我,我需要帮助 在此先感谢我谷歌,但没有得到任何帮助

3 个答案:

答案 0 :(得分:1)

与point.x和point1.x比较,将较小的1作为x,并对y执行相同的操作(与point.y和point1.y较小的1作为y)。将point.x和point1.x之间的差异作为宽度,并对高度执行相同(point.y和point1.y之间的差异)将解决问题

答案 1 :(得分:1)

float x = (point.x < point1.x) ? point.x : point1.x;
float y = (point.y < point1.y) ? point.y : point1.y;
float width = fabsf(point.x - point1.x);
float height = fabsf(point.y - point1.y);
UIView *test1 = [[UIView alloc]initWithFrame:CGRectMake(x, y,width,height)];

答案 2 :(得分:0)

尝试使用下一个计算视图:

float x = MIN(point.x, point1.x);
float y = MIN(point.y, point1.y);
float width = fabsf(point.x - point1.x);
float height = fabsf(point.y - point1.y);
CGRect frame = CGRectMake(x, y, width, height);