2012-08-09 51 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];