J'ai trouvé un moyen avec Swift d'utiliser l'extension et AssociateObject sans sous-classe.
J'utilise une propriété en lecture seule pour désactiver coller/couper mais cet exemple peut être adapté.
Swift 3 mis à jour le 27/11/2016
var key: Void?
class UITextFieldAdditions: NSObject {
var readonly: Bool = false
}
extension UITextField {
var readonly: Bool {
get {
return self.getAdditions().readonly
} set {
self.getAdditions().readonly = newValue
}
}
private func getAdditions() -> UITextFieldAdditions {
var additions = objc_getAssociatedObject(self, &key) as? UITextFieldAdditions
if additions == nil {
additions = UITextFieldAdditions()
objc_setAssociatedObject(self, &key, additions!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
return additions!
}
open override func target(forAction action: Selector, withSender sender: Any?) -> Any? {
if ((action == #selector(UIResponderStandardEditActions.paste(_:)) || (action == #selector(UIResponderStandardEditActions.cut(_:)))) && self.readonly) {
return nil
}
return super.target(forAction: action, withSender: sender)
}
}
Autre Swift (2.2)
import UIKit
var key: Void?
class UITextFieldAdditions: NSObject {
var readonly: Bool = false
}
extension UITextField {
var readonly: Bool {
get {
return self.getAdditions().readonly
}
set {
self.getAdditions().readonly = newValue
}
}
private func getAdditions() -> UITextFieldAdditions {
var additions = objc_getAssociatedObject(self, &key) as? UITextFieldAdditions
if additions == nil {
additions = UITextFieldAdditions()
objc_setAssociatedObject(self, &key, additions!, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
return additions!
}
public override func targetForAction(action: Selector, withSender sender: AnyObject?) -> AnyObject? {
if ((action == Selector("paste:") || (action == Selector("cut:"))) && self.readonly) {
return nil
}
return super.targetForAction(action, withSender: sender)
}
}