简体   繁体   中英

Referencing func that is within another func (swift)

I've got a UIPanGestureRecognizer setup that has a couple of functions inside of it. I want to be able to reference these functions within a button.

The 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()

    }

}

And the Button

@IBAction func LikeButton(_ sender: UIButton) {

}

How can I reference either of the functions swipeLeft and swipeRight inside the button?

The functions are not accessible out of their scope, which is inside your panCard function. Your only option is to move them outside of the scope:

@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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM