完蛋了今天,今天比昨天打完更严重,睡到晚上3点,被身体热醒,起床量个温度37.3好像又不是很高,但热到睡不着,只好走出房间休息的一时半刻,最後终於在四点多睡着,结果今天一天,头都超痛,手臂也会痛,眼压还特别高,这算是变相在惩罚我吧!
今天算是来复习Delegate的使用,因为之後的页面都会使用到Delegate这个概念
什麽是Delegate?
Delegate 比较像是一个Design Pattern,算是一种程序设计的手法
Swift这个程序语言具有POP的性质,那什麽事POP?
POP是Protocol Oriented Programming的意思,可以使用Protocol来完成很多交付任务
先来看一下UML
这张图显示了彼此之间的关系
也知道我们在设计Delegate会有三个要素:
由这三个名词解释,可以知道是由Delegate作为最终的执行者
Protocol作为两个之中的连结
这边是Code码示范,会引用AppCoda的资料,加上我的理解,详细网站会附在下面
要做到的事情是使用Delegate传递资料
将第二视图输入
的资料在第一视图内呈现
// 第一视图
class FirstViewController: UIViewController {
@IBOutlet weak var labelPlatformDetails: UILabel!
@IBOutlet weak var labelDeveloperLanguage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Navigation
@IBAction func actionAddDetail(_ sender: UIButton) {
// 实例化一个第二视图ViewController
guard let secondView = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else {
fatalError("View Controller not found")}
// 将第二视图内的Delegate由这第一视图来执行
secondView.delegate = self //Protocol conformation here
// 切换ViewController
navigationController?.pushViewController(secondView, animated: true)}
}
//MARK: - Protocol Delegate Methods
extension FirstViewController: DeveloperEntryDelegate {
// 将第二视图所回传的资料text 放入第一视图的text内
func textDeveloperPlatform(_ text: String){
labelPlatformDetails.text = "Platform: \(text)" }
// 将第二视图所回传的资料text 放入第一视图的text内
func textDeveloperLanguage(_ text: String) {
labelDeveloperLanguage.text = "Language: \(text)" }
}
// 第二视图
// Delegate Protocol
protocol DeveloperEntryDelegate: AnyObject {
func textDeveloperPlatform(_ text: String)
func textDeveloperLanguage(_ text: String) }
class SecondViewController: UIViewController {
// 产生一个delegate变数,用途负责传送资料
// 使用weak 所以上面的Protocol: AnyObject
weak var delegate: DeveloperEntryDelegate?
@IBOutlet weak var textPlateform: UITextField!
@IBOutlet weak var textLanguage: UITextField!
override func viewDidLoad() {
super.viewDidLoad() }
//MARK: - Action Pass back view Details
@IBAction func actionDone(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
// 使用Delegate传送这个刚刚输入文字的函数
self.delegate?.textDeveloperPlatform(textPlateform.text ?? "")
self.delegate?.textDeveloperLanguage(textLanguage.text ?? "")
}
}
参考网站:
了解 Delegation Pattern 让你更有效率地实作类别之间的沟通!
iOS 开发者指南:透过 Swift 4 学习 Delegates 与 Delegation
Class Diagram to convey the Delegate Pattern
<<: 我们的基因体时代-AI, Data和生物资讯 Day12-基因疗法中之腺病毒载体与机器学习
思路: 我一开始看到这题,感觉他像可以用Greedy解法解的问题,然後又想他是III,所以他也可以用...
大家好~ 接着一起来介接 API 吧! 今天先从 Google Calendar API 开始~ 上...
废话不多说,直接附上code 影片含有程序码详细解说,若有误再烦请告知,谢谢 data(iris) ...
大家好~ 在接下来30天的文章中 我想与大家分享 工作所学 以及学习一些新的东西,例如像是Azure...
哈罗~ 铁人赛终於接近尾声啦(๑´∀ˋ๑) 在 Day14 & Day15 我们介绍了系统入...