4.2.1、swift UIButton传多个值

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

//设置按钮可编辑

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")

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容