【问题标题】:Referencing func that is within another func (swift)引用另一个 func 中的 func (swift)
【发布时间】:2026-01-31 18:40:01
【问题描述】:

我有一个 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?

【问题讨论】:

    标签: swift uibutton uipangesturerecognizer func


    【解决方案1】:

    这些函数在它们的范围之外是不可访问的,它在你的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()
    }
    

    【讨论】:

    • 好的,谢谢。我已将它们与 let card = sender.view 一起移出范围!但随后在该 let 上错误使用未解析的标识符“发件人”。
    • 给函数添加一个参数:func swipeRight(view: NSView),将sender作为参数传递并使用view而不是card
    • 但如果使用 NSView,我会得到“使用未声明的类型 NSView”。我对 swift 真的很陌生,所以发现它有点令人困惑!
    • import Cocoa.