Programming
Swift: Delegate
29 กรกฎาคม 2023 • 1 นาที
0

Table of Contents
Delegate
Delegate คือ การส่งข้อมูลจาก object หนึ่งไปยัง object อีกตัวหนึ่ง โดยที่ object ที่รับข้อมูลจะต้องมีการประกาศ protocol ขึ้นมาก่อน และ object ที่ส่งข้อมูลจะต้องมีการประกาศ delegate และมีการเรียกใช้ method ของ protocol ที่ object ที่รับข้อมูลได้ประกาศไว้
ตัวอย่างการใช้งาน Delegate

protocol MyDelegate {
func didTapButton()
}
class MyView: UIView {
var delegate: MyDelegate?
func buttonTapped() {
delegate?.didTapButton()
}
}
class MyViewController: UIViewController, MyDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let myView = MyView()
myView.delegate = self
}
func didTapButton() {
print("Button tapped")
}
}
Tags:Swift
คลิกเพื่อแสดงความคิดเห็น