【问题标题】:How to make a recursive function call with a long press of a button如何通过长按按钮进行递归函数调用
【发布时间】:2019-07-27 16:30:25
【问题描述】:

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

【问题讨论】:

  • 最难的部分是什么?为什么需要“递归”?

标签: ios swift button


【解决方案1】:

试试这个代码。希望对您有所帮助。

@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.")
        }
    }
}

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2010-09-20
    • 2017-10-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多