[英]Setting anchor point for UIView layer
我有一個UIView子類,我希望能夠在它的superview中移動。 當用戶觸碰的地方了UIView外self.center
但內self.bounds
它“跳躍”,因為我添加新的位置self.center
實現的實際舉措。 為了避免這種行為,我試圖設置一個錨點,讓用戶抓住並拖動視圖在其范圍內的任何位置。
我的問題是,當我計算新的錨點(如下面的代碼所示)沒有任何反應時,視圖根本不會改變位置。 另一方面,如果我將錨點設置為預先計算的點,我可以移動視圖(但當然它會“跳轉”到預先計算的點)。 為什么這不能按預期工作?
謝謝。
- (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;
}
正如Kris Van Bael指出的那樣,你需要在touchsBegan:withEvent:
方法中進行錨點計算, 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;
}
您應該只在TouchBegin上更新anchorpoint。 如果您一直重新計算(TouchMoved),則子視圖不會移動是合乎邏輯的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.