【发布时间】:2011-07-08 01:04:15
【问题描述】:
我有一个视图控件,我打算在里面放置一些控件,例如按钮文本框等...我可以沿 x 轴拖动我的视图,例如:
1)
2)
使用以下代码:
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == ViewMain)
{
CGPoint location = [touch locationInView:self.view];
displaceX = location.x - ViewMain.center.x;
displaceY = ViewMain.center.y;
startPosX = location.x - displaceX;
}
CurrentTime = [[NSDate date] timeIntervalSince1970];
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == ViewMain)
{
CGPoint location = [touch locationInView:self.view];
location.x =location.x - displaceX;
location.y = displaceY;
ViewMain.center = location;
}
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
double time = [[NSDate date] timeIntervalSince1970]-CurrentTime;
UITouch *touch = [[event allTouches] anyObject];
if( [touch view] == ViewMain)
{
CGPoint location = [touch locationInView:self.view];
location.x =location.x - displaceX;
location.y = displaceY;
ViewMain.center = location;
double speed = (ViewMain.center.x-startPosX)/(time*2);
NSLog(@"speed: %f", speed);
}
}
不是我必须添加全局变量:
float displaceX = 0;
float displaceY = 0;
float startPosX = 0;
float startPosY = 0;
double CurrentTime;
我创建这些变量的原因是,当我开始拖动视图时,视图会从我触摸它的点移动,而不是从中间移动。
无论如何,如果我触摸按钮或图像,即使图像在背景上具有透明度,视图也不会拖动。无论视图顶部是否有图像,我都希望能够仍然能够拖动视图。我在想,也许我需要在所有东西上放置一个大的透明视图,但我需要有按钮、图像等。我希望能够像你一样拖动视图:
请注意,无论我第一次触摸应用程序/图像还是文本,我都可以拖动视图。我怎么能这样做?
【问题讨论】:
标签: iphone objective-c ipad uiview drag