Skip to content

Instantly share code, notes, and snippets.

@atom2ueki
Last active April 10, 2018 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atom2ueki/600f1e5a355497d499fdc82e18fdae99 to your computer and use it in GitHub Desktop.
Save atom2ueki/600f1e5a355497d499fdc82e18fdae99 to your computer and use it in GitHub Desktop.
use runtime way to avoid human mistake for clicking on UIButton repeatedly, original article refer to https://icetime17.github.io/2016/07/03/2016-07/iOS-%E5%A6%82%E4%BD%95%E5%9C%A8Swift%E9%A1%B9%E7%9B%AE%E4%B8%AD%E4%BD%BF%E7%94%A8runtime/
import UIKit
// MARK: - UIButton Related
public extension UIButton {
private struct cs_associatedKeys {
static var accpetEventInterval = "cs_acceptEventInterval"
static var acceptEventTime = "cs_acceptEventTime"
}
// 重复点击的间隔
var cs_accpetEventInterval: NSTimeInterval {
get {
if let accpetEventInterval = objc_getAssociatedObject(self, &cs_associatedKeys.accpetEventInterval) as? NSTimeInterval {
return accpetEventInterval
}
return 1.0
}
set {
objc_setAssociatedObject(self, &cs_associatedKeys.accpetEventInterval, newValue as NSTimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var cs_acceptEventTime: NSTimeInterval {
get {
if let acceptEventTime = objc_getAssociatedObject(self, &cs_associatedKeys.acceptEventTime) as? NSTimeInterval {
return acceptEventTime
}
return 1.0
}
set {
objc_setAssociatedObject(self, &cs_associatedKeys.acceptEventTime, newValue as NSTimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
override public class func initialize() {
let before: Method = class_getInstanceMethod(self, #selector(UIButton.sendAction(_:to:forEvent:)))
let after: Method = class_getInstanceMethod(self, #selector(UIButton.cs_sendAction(_:to:forEvent:)))
method_exchangeImplementations(before, after)
}
func cs_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) {
if NSDate().timeIntervalSince1970 - self.cs_acceptEventTime < self.cs_accpetEventInterval {
return
}
if self.cs_accpetEventInterval > 0 {
self.cs_acceptEventTime = NSDate().timeIntervalSince1970
}
self.cs_sendAction(action, to: target, forEvent: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment