首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在UIButton上按下双按钮取消操作?

在UIButton上实现双按钮取消操作,可以通过以下几个步骤:

  1. 首先,在你的UIViewController或者UIView中,创建两个UIButton实例,并设置它们的标题和样式。
代码语言:swift
复制
let button1 = UIButton(type: .system)
button1.setTitle("Button 1", for: .normal)
button1.frame = CGRect(x: 50, y: 100, width: 100, height: 50)

let button2 = UIButton(type: .system)
button2.setTitle("Button 2", for: .normal)
button2.frame = CGRect(x: 200, y: 100, width: 100, height: 50)
  1. 为两个UIButton添加点击事件,并在点击事件中实现双按钮取消操作的逻辑。
代码语言:swift
复制
button1.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside)
button2.addTarget(self, action: #selector(button2Tapped), for: .touchUpInside)

var button1Timer: DispatchSourceTimer?
var button2Timer: DispatchSourceTimer?

@objc func button1Tapped() {
    if button1Timer == nil {
        let queue = DispatchQueue(label: "com.example.button1", attributes: .concurrent)
        button1Timer = DispatchSource.makeTimerSource(queue: queue)
        button1Timer?.schedule(deadline: .now() + 0.5, repeating: 0.5)
        button1Timer?.setEventHandler { [weak self] in
            DispatchQueue.main.async {
                self?.button1.setTitle("Cancel", for: .normal)
            }
        }
        button1Timer?.resume()
    } else {
        button1Timer?.cancel()
        button1Timer = nil
        button1.setTitle("Button 1", for: .normal)
    }
}

@objc func button2Tapped() {
    if button2Timer == nil {
        let queue = DispatchQueue(label: "com.example.button2", attributes: .concurrent)
        button2Timer = DispatchSource.makeTimerSource(queue: queue)
        button2Timer?.schedule(deadline: .now() + 0.5, repeating: 0.5)
        button2Timer?.setEventHandler { [weak self] in
            DispatchQueue.main.async {
                self?.button2.setTitle("Cancel", for: .normal)
            }
        }
        button2Timer?.resume()
    } else {
        button2Timer?.cancel()
        button2Timer = nil
        button2.setTitle("Button 2", for: .normal)
    }
}
  1. 将两个UIButton添加到视图中。
代码语言:swift
复制
view.addSubview(button1)
view.addSubview(button2)

这样,当用户点击Button 1时,按钮的标题会在0.5秒后变为“Cancel”,再次点击会取消计时器并恢复原始标题。同样地,当用户点击Button 2时,按钮的标题会在0.5秒后变为“Cancel”,再次点击会取消计时器并恢复原始标题。

这个示例使用了DispatchSourceTimer来实现计时器功能,它是GCD(Grand Central Dispatch)提供的一种计时器实现方式。你可以根据需要选择其他计时器实现方式,例如使用Timer类或者NSTimer类。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券