0
我正在Xcode中为iPhone制作应用程序,并且它只需要一个框,以便仅在X轴上跟随我的手指。我无法在网上找到任何解决方案,而且我的编码知识也不是很好。IOS触摸跟踪代码
我一直在尝试使用touchesBegan和touchesMoved。
请问有人可以给我写一些代码吗?
我正在Xcode中为iPhone制作应用程序,并且它只需要一个框,以便仅在X轴上跟随我的手指。我无法在网上找到任何解决方案,而且我的编码知识也不是很好。IOS触摸跟踪代码
我一直在尝试使用touchesBegan和touchesMoved。
请问有人可以给我写一些代码吗?
首先你需要的UIGestureRecognizerDelegate
您ViewController.h文件:
@interface ViewController : UIViewController <UIGestureRecognizerDelegate>
@end
然后你申报你的ViewController.m一个UIImageView
,像这样,有BOOL
跟踪,如果触摸事件UIImageView
:
@interface ViewController() {
UIImageView *ballImage;
BOOL touchStarted;
}
然后你初始化UIImageView
上viewDidLoad
:
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"ball.png"];
ballImage = [[UIImageView alloc]initWithImage:image];
[ballImage setFrame:CGRectMake(self.view.center.x, self.view.center.y, ballImage.frame.size.width, ballImage.frame.size.height)];
[self.view addSubview:ballImage];
}
之后,你可以开始做你的修改,什么是最好的,你使用这些方法:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touch_point = [touch locationInView:ballImage];
if ([ballImage pointInside:touch_point withEvent:event])
{
touchStarted = YES;
} else {
touchStarted = NO;
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([touches count]==1 && touchStarted) {
UITouch *touch = [touches anyObject];
CGPoint p0 = [touch previousLocationInView:ballImage];
CGPoint p1 = [touch locationInView:ballImage];
CGPoint center = ballImage.center;
center.x += p1.x - p0.x;
// if you need to move only on the x axis
// comment the following line:
center.y += p1.y - p0.y;
ballImage.center = center;
NSLog(@"moving UIImageView...");
}
}