如何在swift 3中设置Pan Gesture Limit

时间:2017-03-17 10:50:33

标签: ios iphone swift

我采取了两个视图,在该视图中我拍摄了图像视图..显示...下面

enter image description here

我需要设置限制,图像中心不要超出超视图的一边..

我正在尝试使用该代码但是在某些时候工作不正常..

func panImage(tap:UIPanGestureRecognizer) {
    let minx = (abs(Int((tap.view?.superview?.center.x)!)) - ((Int((tap.view?.superview?.frame.width)!))/2))
    let maxx = (abs(Int((tap.view?.superview?.center.x)!)) + ((Int((tap.view?.superview?.frame.width)!))/2))
    let miny = (abs(Int((tap.view?.superview?.center.y)!)) - ((Int((tap.view?.superview?.frame.height)!))/2))
    let maxy = (abs(Int((tap.view?.superview?.center.y)!)) + ((Int((tap.view?.superview?.frame.height)!))/2))
    let translation = tap.translation(in: tap.view)
    if(Int(tap.view!.center.x) > maxx)
    {tap.view!.center.x = CGFloat(maxx)}
    if(Int(tap.view!.center.x) < minx)
    {tap.view!.center.x = CGFloat(minx)}
    if(Int(tap.view!.center.y) > maxy)
    {tap.view!.center.y = CGFloat(maxy)}
    if(Int(tap.view!.center.y) < miny)
    {tap.view!.center.y = CGFloat(miny)}

    if((Int(tap.view!.center.x) >= minx && Int(tap.view!.center.x) <= maxx ) && (Int(tap.view!.center.y) <= maxy && Int(tap.view!.center.y) >= miny))
    {
        tap.view!.center = CGPoint(x: tap.view!.center.x + translation.x, y: tap.view!.center.y + translation.y)
        tap.setTranslation(CGPoint(x: 0.0, y: 0.0), in:tap.view)
    }
}

1 个答案:

答案 0 :(得分:0)

我正在尝试正常运行的代码..

这里

 func panImage(tap:UIPanGestureRecognizer) {
    let minx = 0
    let maxx = minx + Int((tap.view?.superview?.frame.size.width)!)
    let miny = 0
    let maxy = miny + Int((tap.view?.superview?.frame.size.height)!)
    let translation = tap.translation(in: tap.view)
    if(Int(tap.view!.center.x) > maxx)
    {tap.view!.center.x = CGFloat(maxx)}
    if(Int(tap.view!.center.x) < minx)
    {tap.view!.center.x = CGFloat(minx)}
    if(Int(tap.view!.center.y) > maxy)
    {tap.view!.center.y = CGFloat(maxy)}
    if(Int(tap.view!.center.y) < miny)
    {tap.view!.center.y = CGFloat(miny)}

    if((Int(tap.view!.center.x) >= minx && Int(tap.view!.center.x) <= maxx ) && (Int(tap.view!.center.y) <= maxy && Int(tap.view!.center.y) >= miny))
    {
        tap.view!.center = CGPoint(x: tap.view!.center.x + translation.x, y: tap.view!.center.y + translation.y)
        tap.setTranslation(CGPoint(x: 0.0, y: 0.0), in:tap.view)
    }
}