我有一个UIView我试图在屏幕上上下移动,但是我只希望它能够平移,这样当它处于正常位置(0,0)时你就无法将视图向下拖动
我试图检测识别器的中心何时不是视图高度的一半,但视图是不可移动的,中心总是高度的一半(在这种情况下为230)。
有什么想法吗?
- (IBAction)panDetected:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
NSLog(@"\ncenter.y: %f\ntranslation.y: %f\n", recognizer.view.center.y, translation.y);
if (recognizer.view.center.y > ([[UIScreen mainScreen] bounds].size.height - 20)/2) {
return;
}
recognizer.view.center = CGPointMake(recognizer.view.center.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
答案 0 :(得分:3)
使用CGRectContainsPoint(rect, point)
而不是手动计算点是否在视图范围内。这对我有用,我喜欢它,因为它更短,更易读:
func handlePan(pan: UIPanGestureRecognizer) {
switch pan.state {
case .Began:
if CGRectContainsPoint(self.pannableView.frame, pan.locationInView(self.pannableView)) {
// Gesture started inside the pannable view. Do your thing.
}
}
答案 1 :(得分:1)
CGPoint translation = [recognizer translationInView:self.view];
CGPoint finalpoint = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y+ translation.y);
//limit the boundary
if ((recognizer.view.frame.origin.x>0 && translation.x > 0) || (recognizer.view.frame.origin.x + recognizer.view.frame.size.width<=320 && translation.x < 0))
finalpoint.x = recognizer.view.center.x;
if ((recognizer.view.frame.origin.y>0 && translation.y > 0) || (recognizer.view.frame.origin.y + recognizer.view.frame.size.height<=self.view.frame.size.height && translation.y < 0))
finalpoint.y = recognizer.view.center.y;
//set final position
recognizer.view.center = finalpoint;
[recognizer setTranslation:CGPointZero inView:self.view];
答案 2 :(得分:0)
尝试
CGPoint translation = [recognizer translationInView:self.view];
if (translation.x+recognizer.view.frame.origin.x<0||translation.y+recognizer.view.frame.origin.y<0)
{
return;
}
recognizer.view.center = CGPointMake(recognizer.view.center.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
答案 3 :(得分:0)
recognizer.view.center = CGPointMake(recognizer.view.center.x, MAX(recognizer.view.center.y + translation.y, ([[UIScreen mainScreen] bounds].size.height - 20)/2));