2012-08-09 54 views
0

我有一个UIView和他的顶部我有UIButton,UITableView和UINavigationBar。我想要做的是,当你点击UIButton并拖动它时,所有视图将只移动到左侧,直到屏幕结束。我的意思是,您可以将视图拖动到左侧,当您停止触摸时,视图将停止在您的手指停止触摸屏幕的位置。UITouch,拖放并没有在所有工作

我不能这样做,他只给我看“触动开始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]; 
} 

回答

2
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    NSLog("Touches Began 1"); 
for (UITouch *touch in touches) { 
    //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]; 
for (UITouch *touch in touches) { 
    CGPoint touchLocation = [touch locationInView:self.view]; 

    if (CGRectContainsPoint(btnOpen.frame, touchLocation)) 
    { 
     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; 
    } 
} 
} 

尝试这样我认为这将是对你有所帮助。

2

您所要求的触摸的坐标有关

CGPoint touchLocation = [touch locationInView:self.view]; 

然后你问主视图的框架,如果touchLocation的位置的按钮框架

的框架内
if (CGRectContainsPoint(btnOpen.frame, touchLocation)) 

换句话说。您正在检查触摸是否在按钮的范围内,但您通过在主视图上进行的触摸坐标来检查,而不是按钮。

因此,这是你应该做的:

CGPoint touchLocation = [touch locationInView:btnOpen];