2015-12-27 32 views
2

我分配捏手势的UIView:如何防止以超过对捏放其父边界 - 迅速

myView.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: "handlePinch:")) 

此功能将缩放的UIView:

func handlePinch(recognizer : UIPinchGestureRecognizer) { 
    if let view = recognizer.view { 
     view.transform = CGAffineTransformScale(view.transform, 
           recognizer.scale, recognizer.scale) 
     recognizer.scale = 1 
    } 
} 

但规模在父视图内的不限于。当我尝试缩小它时也没有限制,它会缩放直到它消失。

灰色的观点是父

Desciption

我的问题是

怎样才可以超过对规模达父框架和规模上消失下来防止

+0

如果比例<0.2(或您的限制),只需使用if语句检查recognizer.scale,如果它低于此限制,则将其设置为0.2? –

回答

4

你可以使用这样的事情:

if let view = recognizer.view, parent = recognizer.view.superview { 

    // this will only let it scale to half size 
    let minimumThreshold: CGFloat = 0.5 
    var scale: CGFloat = recognizer.scale 

    // assuming your view is square, which based on your example it is 
    let newSize = view.frame.height * scale 

    // prevents the view from growing larger than the smallest dimension of the parent view 
    let allowableSize = min(parent.frame.height, parent.frame.width) 
    let maximumScale: CGFloat = allowableSize/view.frame.height 

    // change scale if it breaks either bound 
    if scale < minimumThreshold { 
     print("size is too small") 
     scale = minimumThreshold 
    } 

    if newSize > allowableSize { 
     print("size is too large") 
     scale = maximumScale 
    } 

    // apply the transform 
    view.transform = CGAffineTransformMakeScale(scale, scale) 
} 

这里的关键是要在下限基础上的偏好,并根据您的视图的初始大小的父的大小比例的上限决定。通过这样做,视图不会缩小到比想要的要小,因为假定用户不应该缩小到由于捏住困难而无法调整大小的点。另外,这个观点不应该被允许无限缩放,从而溢出其界限。这个检查就是这样做的,因为它只允许你指定的一系列尺寸由用户的交互设置。

+0

虽然此代码可能回答问题,但提供有关* why *和/或* how *代码如何回答问题的其他上下文可提高其长期价值。 –

+0

与我们可以设置缩小图像的50%相同。如果我们可以发布代码 – JAck