【swift_4】swift之代理传值(delegate的用法)
2015-06-23 14:06
477 查看
具体的代码,详见Demo:链接: http://pan.baidu.com/s/1gdkyWE3 密码: 4mhv
rootViewController
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, y: 100, 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,y:200,width:200,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入门第一章常量、变量
- swift初见
- Swift基础教程
- swift中使用CoreData实现增删查改
- 利用Swift之协议语法实现页面间的传值功能
- swift switch Double
- swift 编译预定义 --不知道怎么定义,但是可以#if
- Swift之?和!
- 苹果公司的新的编程语言 Swift 高级语言()两--基本数据类型
- swift 单例模式
- 【swift总结】集合
- 4 Swift函数
- Swift 通用类型和通用函数 | Generic type and function
- 【swift总结】字符串和字符
- Swift 编程语言新手教程
- 自学Swift-斯坦福笔记整理(六)
- 自学Swift-斯坦福笔记整理(五)
- Swift基本数据类型(一)
- swift oerator[](int i)
- swift 传值 引用 (=、&)