ในบทความนี้ คุณจะเรียนรู้เกี่ยวกับ delegates และการสร้าง delegates ก่อนอื่น
Delegate คืออะไร?
Delegate เป็นคำง่ายๆ ที่หมายถึงการสื่อสารระหว่างอ็อบเจ็กต์ เป็นวิธีง่ายในการเชื่อมต่ออ็อบเจ็กต์และสื่อสารระหว่างพวกเขา
Delegate ทำงานอย่างไร?
Delegate ถูกสร้างด้วย protocol Protocol ถูกประกาศในคลาส ซึ่งภายในจะมี event บางอย่างเกิดขึ้น ที่ควรแจ้งเตือนคลาสอื่นๆ ใน protocol เราเขียนการประกาศฟังก์ชัน และนิยามภายใน calling class
วิธีสร้าง Delegate
เราจะทำด้วยโปรเจกต์ตัวอย่าง
ขั้นตอนที่ต้องทำ -
สร้างคลาส ชื่อ FirstViewController สร้างอีกคลาสหนึ่งชื่อ SecondViewController สร้าง View controllers ของพวกเขาใน storyboard
ประกาศ protocol ใน SecondViewController Protocol ประกาศนอก class หรือ object ใดๆ
protocol SecondViewControllerDelegate { func buttonPressedInVC2() }ใน SecondViewController สร้าง optional object ของ delegate ที่เราสร้าง
var delegate: SecondViewControllerDelegate?
เราต้องเรียกฟังก์ชันที่ประกาศใน protocol เมื่อมี event เกิดขึ้นใน SecondViewController มาสร้าง event ที่เกิดเมื่อปุ่มถูกกดใน second view controller
@IBAction func buttonTapped(_ sender: UIButton) { self.delegate?.buttonPressedInVC2() self.navigationController?.popViewController(animated: true) }นี่คือทั้งหมดที่ต้องการใน SecondViewController ตอนนี้มาทำงานบน FirstViewController
เราต้อง conform/implement FirstViewController ให้เป็น SecondViewControllerDelegate และมันจะขอให้เพิ่ม protocol stubs อัตโนมัติ
extension FirstViewController: SecondViewControllerDelegate { func buttonPressedInVC2() { } }ภายใน protocol ที่เรา implement เราควรเขียนโค้ดที่เราต้องการให้รันเมื่อ delegate action นี้เกิดขึ้น
มาสร้าง label ใน FirstViewController และเปลี่ยนข้อความเมื่อ delegate method ถูกเรียก
extension FirstViewController: SecondViewControllerDelegate { func buttonPressedInVC2() { self.lblOne.text = "Delegate Implemented" } }ขั้นตอนสุดท้ายคือ delegate object ใน SecondViewController เป็น optional และจะเป็น nil จนกว่าจะถูก assign ดังนั้น ใน FirstViewController เราจะ assign object นั้นขณะไปจาก FirstViewController ไป SecondViewController
มาสร้างปุ่มใน FirstViewController สำหรับนั้น
@IBAction func goToNextVC(_ sender: Any) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController vc.delegate = self self.navigationController?.pushViewController(vc, animated: true) }และถ้าคุณยังไม่รู้ เราต้อง embed FirstViewController ใน Navigation Controller มารันแอปและดูว่ามันทำงานอย่างไร
