我有一個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;
}
確保您對anchorPoint有完全的瞭解:http://stackoverflow.com/a/22188420/550393 – 2cupsOfTech 2014-03-28 03:03:14