1. 程式人生 > >swift4 防止button重複點選

swift4 防止button重複點選

swift4中的runtime機制的initialize()這個方法已經被廢棄了  所以需要吧自己寫的那個方法,在Appdelegate 中呼叫此方法

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey

: Any]?) -> Bool {

        //在此處呼叫

UIButton.initializeMethod()

// Override point for customization after application launch.

returntrue

}

......

}


import UIKit

publicextensionUIButton{

public struct AssociatedKeys{

static var defaultInterval : TimeInterval = 5 //間隔時間

static var A_customInterval = "customInterval"

static

var A_ignoreInterval = "ignoreInterval"

}

var customInterval: TimeInterval{

get{

let A_customInterval = objc_getAssociatedObject(self, &AssociatedKeys.A_customInterval)

if let time = A_customInterval{

return time as! TimeInterval

}else{

returnAssociatedKeys.defaultInterval

}

}

set{

objc_setAssociatedObject(

self, &AssociatedKeys.A_customInterval, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

}

}

var ignoreInterval: Bool{

get{

return (objc_getAssociatedObject(self, &AssociatedKeys.A_ignoreInterval) != nil)

}

set{

objc_setAssociatedObject(self, &AssociatedKeys.A_ignoreInterval, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)

}

}

    //由於在swift4中 initialize()這個方法已經被廢棄了  所以需要自己寫一個方法,並在Appdelegate 中呼叫此方法

public class func initializeMethod(){

if self == UIButton.self{

let systemSel = #selector(UIButton.sendAction(_:to:for:))

let sSel = #selector(UIButton.mySendAction(_: to: for:))

let systemMethod = class_getInstanceMethod(self, systemSel)

let sMethod = class_getInstanceMethod(self, sSel)

let isTrue = class_addMethod(self, systemSel, method_getImplementation(sMethod!), method_getTypeEncoding(sMethod!))

if isTrue{

class_replaceMethod(self, sSel, method_getImplementation(systemMethod!), method_getTypeEncoding(systemMethod!))

}else{

method_exchangeImplementations(systemMethod!, sMethod!)

}

}

}

@objc private dynamic func mySendAction(_ action: Selector, to target: Any?, for event: UIEvent?){

if !ignoreInterval{

isUserInteractionEnabled = false

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+customInterval, execute: {

self.isUserInteractionEnabled = true

})

}

mySendAction(action, to: target, for: event)

}

}