我有一个 UIView,在他上面我有 UIButton、UITableView 和 UINavigationBar。我想要做的是,当您单击 UIButton 并拖动它时,所有视图将仅移动到左侧,直到屏幕结束。我的意思是您可以将视图向左拖动,当您停止触摸时,视图将在您的手指停止触摸屏幕的位置停止。
我做不到,他只给我看“Touches Began 1”,仅此而已。我的问题似乎在这里?
非常感谢大家!
float oldX, oldY;
BOOL dragging;
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
NSLog("Touches Began 1");
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(btnOpen.frame, touchLocation))
{
NSLog("Touches Began 2");
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
}
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (dragging)
{
NSLog("Dragging!");
CGRect frame = mainView.frame;
frame.origin.x = mainView.frame.origin.x + touchLocation.x - oldX;
frame.origin.y = mainView.frame.origin.y + touchLocation.y - oldY;
mainView.frame = frame;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog("Touches Ended!");
dragging = NO;
}
- (void)viewDidLoad
{
[btnOpen addTarget:self action:@selector(touchesBegan:withEvent:) forControlEvents: UIControlEventTouchDown];
[btnOpen addTarget:self action:@selector(touchesMoved:withEvent:) forControlEvents: UIControlEventTouchDragInside];
[btnOpen addTarget:self action:@selector(touchesEnded:withEvent:) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
}