IOS触摸跟踪代码 [英] IOS touch tracking code
问题描述
我正在 Xcode 中为 iPhone 制作一个应用程序,它需要一个框来仅在 X 轴上跟随我的手指.我在网上找不到任何解决方案,而且我的编码知识也不是很好.
I'm making an app for iPhone in Xcode, and It requires a box to follow my finger only on the X axis. I couldn't find any solution online to this, and my coding knowledge isn't that great.
我一直在尝试使用 touchesBegan 和 touchesMoved.
I've been trying to use touchesBegan and touchesMoved.
有人可以帮我写一些代码吗?
Could someone please write me up some code please?
推荐答案
首先你需要 UIGestureRecognizerDelegate
在你的 ViewController.h 文件中:
First you need the UIGestureRecognizerDelegate
on your ViewController.h file:
@interface ViewController : UIViewController <UIGestureRecognizerDelegate>
@end
然后在 ViewController.m 上声明一个 UIImageView
,就像这样,使用 BOOL
来跟踪内部是否发生触摸事件你的 UIImageView
:
Then you declare an UIImageView
on your ViewController.m, like so, with a BOOL
to track if a touch event is occurring inside your UIImageView
:
@interface ViewController () {
UIImageView *ballImage;
BOOL touchStarted;
}
然后在viewDidLoad
上初始化UIImageView
:
- (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];
}
之后,您可以开始使用这些方法对最适合您的内容进行修改:
After that you can start doing your modifications to what's best for you using these methods:
-(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...");
}
}
这篇关于IOS触摸跟踪代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!