5

我有一个 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];
}
4

4 回答 4

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.
        }
}
于 2014-10-31T07:29:58.370 回答
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];
于 2013-07-19T09:37:23.227 回答
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];
于 2012-12-14T15:31:08.437 回答
0
recognizer.view.center = CGPointMake(recognizer.view.center.x, MAX(recognizer.view.center.y + translation.y, ([[UIScreen mainScreen] bounds].size.height - 20)/2));
于 2012-12-21T02:54:30.970 回答