我想知道在使用GestureRecognizer时是否有办法在我的超视图中限制我的UIView的移动。
例如。我有一个UIImageview我向其添加UIPanGestureRecognizer与动作panPiece。我通过以下方式调整其中心,以避免其移出超视图。但它无法正常工作。
-(CGPoint) centerWithBounds:(CGPoint)center andViewFrame:(CGRect)viewFrame andBoundingFrame:(CGRect)boundingFrame{
CGFloat lowerXBound = boundingFrame.origin.x + ( viewFrame.size.width/2 );
CGFloat higherXBound = boundingFrame.origin.x + boundingFrame.size.width - ( viewFrame.size.width/2 );
CGFloat lowerYBound = boundingFrame.origin.y + ( viewFrame.size.height/2 );
CGFloat higherYBound = boundingFrame.origin.y + boundingFrame.size.height - ( viewFrame.size.height/2 );
if ( center.x < lowerXBound) {
center.x = lowerXBound;
}
if ( center.x > higherXBound ){
center.x = higherXBound;
}
if ( center.y < lowerYBound) {
center.y = lowerYBound;
}
if ( center.y > higherYBound ){
center.y = higherYBound;
}
return center;
}
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:[piece superview]];
CGPoint translatedCenter = CGPointMake([piece center].x + translation.x, [piece center].y + translation.y);
CGPoint center = [self centerWithBounds:translatedCenter andViewFrame:[piece frame] andBoundingFrame:[[piece superview] frame]];
[piece setCenter:center];
[gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}
}
感谢代码帮助。
答案 0 :(得分:0)
您只需要将属性clipsToBounds(将其设置为YES)用于superview。早先有同样的问题。在那之后完美地运作。
答案 1 :(得分:-1)