引用另一个func(swift)中的func

时间:2017-04-25 21:06:20

标签: swift uibutton uipangesturerecognizer func

我有一个UIPanGestureRecognizer设置,里面有几个功能。我希望能够在一个按钮中引用这些功能。

UIPanGestureRecognizer

  @IBAction func panCard(_ sender: UIPanGestureRecognizer) {

    let card = sender.view!
    let point = sender.translation(in: view)

    card.center = CGPoint(x: view.center.x + point.x, y: view.center.y + point.y)

    func swipeLeft() {
        //move off to the left
        UIView.animate(withDuration: 0.3, animations: {
            card.center = CGPoint(x: card.center.x - 200, y: card.center.y + 75)
            card.alpha = 0
        })
    }

    func swipeRight() {
        //move off to the right
        UIView.animate(withDuration: 0.3, animations: {
            card.center = CGPoint(x: card.center.x + 200, y: card.center.y + 75)
            card.alpha = 0
        })
    }

    if sender.state == UIGestureRecognizerState.ended {

        if card.center.x < 75 {
            swipeLeft()
            return
        } else if card.center.x > (view.frame.width - 75) {
            swipeRight()
            return
        }

        resetCard()

    }

}

按钮

@IBAction func LikeButton(_ sender: UIButton) {

}

如何在按钮内引用swipeLeft和swipeRight中的任何一个函数?

1 个答案:

答案 0 :(得分:4)

这些功能无法在其范围内访问,该范围位于panCard功能中。您唯一的选择是将它们移到范围之外:

@IBAction func panCard(_ sender: UIPanGestureRecognizer) {

    let card = sender.view!
    let point = sender.translation(in: view)

    card.center = CGPoint(x: view.center.x + point.x, y: view.center.y + point.y)

    if sender.state == UIGestureRecognizerState.ended {

        if card.center.x < 75 {
            swipeLeft()
            return
        } else if card.center.x > (view.frame.width - 75) {
            swipeRight()
            return
        }

    resetCard()

    }
}

func swipeRight() {
    //move off to the right
    UIView.animate(withDuration: 0.3, animations: {
        card.center = CGPoint(x: card.center.x + 200, y: card.center.y + 75)
        card.alpha = 0
    })
}

func swipeLeft() {
    //move off to the left
    UIView.animate(withDuration: 0.3, animations: {
        card.center = CGPoint(x: card.center.x - 200, y: card.center.y + 75)
        card.alpha = 0
    })
}

@IBAction func LikeButton(_ sender: UIButton) {
// swipeLeft()
// swipeRight()
}