Swift 2.2 协议和代理
一:代理
两个类之间的传值,类A调用类B的方法,类B在执行过程中遇到问题通知类A,这时候我们需要用到代理(Delegate)。
比如:控制器(Controller)与控制器(Controller)之间的传值,从C1跳转到C2,再从C2返回到C1时需要通知C1更新UI或者是做其它的事情,这时候我们就用
到了代理(Delegate)传值。
二:协议
上面说的两个界面,或者类之间的值传递,你就把协议当成他们之间的合同,就理解了。
下面看看Swift代码怎么写协议,为了方便阅读,我这里把整个Swift文件代码插入了,不是只写了一个方法。这样我自己觉得阅读性更强一点!import UIKit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // 协议的创建 protocol youname { func younameis ( name : NSString ) - > Void } class ProfileViewController : UIViewController { // 声明一个协议类型的代理变量 var delegate : youname ! // 这个方法写在这里只是为了在后面的界面设置了代理之后,去调用这个方法。 func delegatetest () - > Void { self . delegate . younameis ( "caoxiaocaoxiangni" ) } // 这里的思路其实和我们OC写的思路是一样的! override func viewDidLoad () { super . viewDidLoad () self . view . backgroundColor = UIColor . whiteColor () } override func didReceiveMemoryWarning () { super . didReceiveMemoryWarning () // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } |
我们来看看第二个界面里面是怎么写的,上面一个是 ProfileViewController 控制器,push 到下一个控制器,MEViewController 中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import UIKit class MEViewController : UIViewController , youname { override func viewDidLoad () { super . viewDidLoad () // Do any additional setup after loading the view. // 创建了变量,设置代理,遵守协议,调用方法。 let you : ProfileViewController = ProfileViewController () you . delegate = self you . delegatetest () } // 上个控制器里面 delegatetest 这个方法中,我们又设置了让它的代理(其实就是MEViewController)调用 younameis 方法,前面界面的参数 caoxiaocao 也就传了过来! func younameis ( name : NSString ) { print ( name ) // caoxiaocao } override func didReceiveMemoryWarning () { super . didReceiveMemoryWarning () // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } |
这样子,我也就完整的吧上个界面的值,传到了这个界面中来了。整个思路和OC的差不多。
## 努力做一个合格的程序员。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话