2011-01-27 77 views
5

我有一個UIView子類,我希望能夠在它的超級視圖中移動。當用戶觸摸self.center之外的某個地方的UIView,但在self.bounds之內時,它會「跳躍」,因爲我將新位置添加到self.center以實現實際移動。爲了避免這種行爲,我試圖設置一個錨點,讓用戶在任何地方抓住並拖動視圖。設置UIView圖層的錨點

我的問題是,當我計算新的錨點(如下面的代碼所示)沒有任何反應,視圖根本不會改變位置。另一方面,如果我將錨點設置爲預先計算的點,則可以移動視圖(但當然它會「跳轉」到預先計算的點)。這是怎麼回事?

謝謝。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    // Only support single touches, anyObject retrieves only one touch 
    UITouch *touch = [touches anyObject]; 
    CGPoint locationInView = [touch locationInView:self]; 

    // New location is somewhere within the superview 
    CGPoint locationInSuperview = [touch locationInView:self.superview]; 

    // Set an anchorpoint that acts as starting point for the move 
    // Doesn't work! 
    self.layer.anchorPoint = CGPointMake(locationInView.x/self.bounds.size.width, locationInView.y/self.bounds.size.height); 
    // Does work! 
    self.layer.anchorPoint = CGPointMake(0.01, 0.0181818); 

    // Move to new location 
    self.center = locationInSuperview; 
} 
+1

確保您對anchorPoint有完全的瞭解:http://stackoverflow.com/a/22188420/550393 – 2cupsOfTech 2014-03-28 03:03:14

回答

12

正如Kris Van Bael指出的那樣,您需要在touchsBegan:withEvent:方法中執行定位點計算以避免移動。此外,由於更改圖層的anchorPoint將移動視圖的初始位置,因此必須在視圖的點center上添加偏移量以避免第一次觸摸後的「跳躍」。

您可以通過計算(和添加到您的視圖的center點),根據最初和最後的anchorPoints之間的差額抵消做到這一點(通過您的視圖的寬度/高度乘以),或者你可以設置視圖的center初始接觸點。

像這樣的東西可能:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 
    CGPoint locationInView = [touch locationInView:self]; 
    CGPoint locationInSuperview = [touch locationInView:self.superview]; 

    self.layer.anchorPoint = CGPointMake(locationInView.x/self.frame.size.width, locationInView.y/self.frame.size.height); 
    self.center = locationInSuperview; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 
    CGPoint locationInSuperview = [touch locationInView:self.superview]; 

    self.center = locationInSuperview; 
} 

更多來自蘋果的文檔hereanchorPoint的信息和相似的,所以問題,我引用here

0

您應該只在TouchBegin上更新定位點。如果您一直重新計算(TouchMoved),則子視圖不會移動是合乎邏輯的。

+0

謝謝你,當然你是對的!此外,重新計算錨點顯然沒有意義,因爲當實際移動開始時,用戶不會在邊界內移動手指。 然而,當山姆在回答中突出顯示時,將anchorPoint的更新更改爲touhesBegan會出現偏移問題。 – Oskar 2011-01-28 09:12:40