如何在平移手势后立即调用函数?

时间:2016-10-10 12:08:07

标签: ios swift3

请知道我是Swift和IOS的新手。我正在使用平移手势来移动标签。完成后,我想自动添加一个新标签。我试图在平移功能结束时调用一个函数,但是当添加新标签时,我移动的标签会移出屏幕。我试图使用" panGR.state.rawValue == 3"," panGR.state == UIGestureRecognizerState.ended"和一个计时器 - 没有成功。请帮忙。

希望这是解释问题所需的代码:

func initGestureRecognizers() {

    let panGR = UIPanGestureRecognizer(target: self, action:
    #selector(ShapeView.didPan(_:)))
    addGestureRecognizer(panGR) 

}

func didPan(_ panGR: UIPanGestureRecognizer) {

    self.superview!.bringSubview(toFront: self)
    var size: CGFloat = 53
    var translation = panGR.translation(in: self)
    translation = translation.applying(self.transform)
    self.center.x += translation.x
    self.center.y += translation.y
    panGR.setTranslation(CGPoint.zero, in: self)

    if panGR.state.rawValue == 1 { // save the last position
        let startX = self.center.x
        let startY = self.center.y
    }

    if panGR.state.rawValue == 3 {  // when move is finished

        // this will remove ability to move tile
        removeGestureRecognizer(panGR)

        // the following code should replace the moved tile,
        // with a new tile, but leave the moved tile where it is.

        // BUT - it moves the moved tile to coordinates (x=0,y=0), if 
        // the following 2 lines are executed.

        self.center.x = 0   
        self.center.y = 0

        // if the above 2 lines are not executed, the new tile
        // does not get displayed

        replaceMovedTile()

    }
}

func replaceMovedTile() {
        // position new tile
        let tapPoint = CGPoint(x: 46 + 22, y: 596 + 22)  
        let shapeView = ShapeView(origin: tapPoint)   
        addSubview(shapeView)
}

1 个答案:

答案 0 :(得分:0)

addSubview是为您创建的功能吗? 如果没有,请将self.view置于

之前
self.view.addSubview(shapeView)