在UIButton上实现双按钮取消操作,可以通过以下几个步骤:
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)
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)
}
}
view.addSubview(button1)
view.addSubview(button2)
这样,当用户点击Button 1时,按钮的标题会在0.5秒后变为“Cancel”,再次点击会取消计时器并恢复原始标题。同样地,当用户点击Button 2时,按钮的标题会在0.5秒后变为“Cancel”,再次点击会取消计时器并恢复原始标题。
这个示例使用了DispatchSourceTimer来实现计时器功能,它是GCD(Grand Central Dispatch)提供的一种计时器实现方式。你可以根据需要选择其他计时器实现方式,例如使用Timer类或者NSTimer类。
领取专属 10元无门槛券
手把手带您无忧上云