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...");
}
}