classExtensionButton:UIButton{
varnewDict =NSMutableDictionary()
}
//方法一
funcdeliverBtn() {
letbtn =ExtensionButton(frame:CGRect(x:100, y:350, width:50, height:50))
self.view.addSubview(btn)
btn.backgroundColor=UIColor.yellow
btn.newDict=NSMutableDictionary(dictionary: ["name":"Tom","age":18])
btn.addTarget(self, action:#selector(deliverMuchData(sender:)), for: .touchUpInside)
}
funcdeliverMuchData(sender:ExtensionButton){
letdict = sender.newDict
letname = dict["name"]
print(sender.newDict,name ??"")
}
//方法二
funcrectBtn() {
letrectBtn =UIButton(frame:CGRect(x: (mainWith-80)/2, y:80, width:80, height:80))
self.view.addSubview(rectBtn)
rectBtn.backgroundColor=UIColor.red
//設(shè)置按鈕可編輯
rectBtn.clipsToBounds=true
rectBtn.layer.cornerRadius=40
rectBtn.setImage(UIImage.init(named:"我的"), for: .normal)
rectBtn.layer.borderColor=UIColor.black.cgColor
rectBtn.layer.borderWidth=2
letname:NSString="Tom"
letage:Int=18
objc_setAssociatedObject(rectBtn,ViewController.RuntimeKey.nameKey, name, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(rectBtn,ViewController.RuntimeKey.ageKey, age, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
rectBtn.addTarget(self, action:#selector(touchActions(sender:)), for: .touchUpInside)
}
structRuntimeKey {
staticletnameKey =UnsafeRawPointer.init(bitPattern:"name".hashValue)
staticletageKey =UnsafeRawPointer.init(bitPattern:"age".hashValue)
}
functouchActions(sender:UIButton){
letname =objc_getAssociatedObject(sender,ViewController.RuntimeKey.nameKey)
letweight =objc_getAssociatedObject(sender,ViewController.RuntimeKey.ageKey)
print(name ??"a",weight ??"1")
}