如何长按按钮进行递归函数调用

时间:2019-07-27 16:30:25

标签: ios swift button

我有一个控制声音的按钮,我想制作它,以便在长按该按钮时声音会逐渐增加。怎么做? (我有增加和减少声音的逻辑)

1 个答案:

答案 0 :(得分:0)

尝试此代码。希望对您有帮助。

@IBOutlet weak var volumeUpButton: UIButton!

var shouldIncreaseVolume: Bool = false { didSet { if shouldIncreaseVolume { volumeLoop() } } }

override func viewDidLoad() {
    super.viewDidLoad()

    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(increaseVolumeHandler))
    volumeUpButton.addGestureRecognizer(longPress)
}

@objc
func increaseVolumeHandler(sender: UILongPressGestureRecognizer) {
    switch sender.state {
    case .began:
        shouldIncreaseVolume = true
        break

    default:
        shouldIncreaseVolume = false
        break
    }
}

func volumeLoop() {
    // You can alter the time from 0.1 to any value as per your requirement.
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        if self.shouldIncreaseVolume {
            self.volumeLoop()
            print("(+) Call increase volume method here.")
        }
    }
}

谢谢