具体的代码,详见Demo:链接: http://pan.baidu.com/s/1gdkyWE3 密码: 4mhv
class VIEwController: UIVIEwController,GetMessageDelegate{ var _button:UIbutton? var _label:UILabel? overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() self.Title = "RootVIEwController" //创建label 用来接收传过来的值 _label = UILabel(frame: CGRect(x: 50,y: 100,wIDth: 220,height: 44)) _label?.text = "get message from next page" _label?.textAlignment = NSTextAlignment.Center _label?.backgroundcolor = UIcolor.cyancolor() self.vIEw.addSubvIEw(_label!) //创建button 点击跳转到下一个界面 _button = UIbutton(frame:CGRect(x:60,y:200,wIDth:200,height:44)) _button?.setTitle("go to next page",forState: UIControlState.normal) _button?.setTitlecolor(UIcolor.yellowcolor(),forState: UIControlState.normal) _button?.backgroundcolor = UIcolor.bluecolor() _button?.addTarget(self,action: "nextPage",forControlEvents: UIControlEvents.touchUpInsIDe) self.vIEw.addSubvIEw(_button!) } //push func nextPage() { let nextVC = NextVIEwController() //指定代理 nextVC.delegate = self self.navigationController!.pushVIEwController(nextVC,animated:true) } //接收传过来的值 func getMessage(controller:NextVIEwController,string:String) { _label?.text = string if(string == "") { _label?.text = "null" } }}
secondVIEwController
//创建协议protocol GetMessageDelegate:NSObjectProtocol{ //回调方法 传一个String类型的值 func getMessage(controller:NextVIEwController,string:String)}class NextVIEwController: UIVIEwController{ var delegate:GetMessageDelegate? var _textFIEld:UITextFIEld? overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() self.Title = "SecondVIEwController" self.vIEw.backgroundcolor = UIcolor.whitecolor() //创建textFIEld 用来输入要传的值 _textFIEld = UITextFIEld(frame: CGRect(x: 60,wIDth: 200,height: 44)) _textFIEld?.borderStyle = UITextborderStyle.RoundedRect _textFIEld?.placeholder = "input sth to send back" self.vIEw.addSubvIEw(_textFIEld!) //创建返回的button var mybutton = UIbutton(frame:CGRect(x:60,height:44)) mybutton.center = CGPointMake(160,200) mybutton.setTitle("send message back",forState:.normal) mybutton.addTarget(self,action:"goBack",forControlEvents:.touchUpInsIDe) mybutton.backgroundcolor = UIcolor.bluecolor() self.vIEw.addSubvIEw(mybutton) } func goBack() { //调用代理方法 if((delegate) != nil) { delegate?.getMessage(self,string:_textFIEld!.text) self.navigationController?.popToRootVIEwControllerAnimated(true) } }}总结
以上是内存溢出为你收集整理的【swift_4】swift之代理传值(delegate的用法)全部内容,希望文章能够帮你解决【swift_4】swift之代理传值(delegate的用法)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)