Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Thiết lập delegate đơn giản để giao tiếp giữa hai view controller trong iPhone


Trong bài này, bạn học về delegate và tạo delegate. Trước hết,

Delegate là gì?

Delegate là thuật ngữ đơn giản chỉ giao tiếp giữa các đối tượng. Đây là cách đơn giản kết nối đối tượng và giao tiếp giữa chúng.

Delegate hoạt động như thế nào?

Delegate được tạo với sự giúp đỡ của protocol (giao thức). Một protocol được khai báo trong class, bên trong sẽ có sự kiện xảy ra, cần thông báo cho các class khác. Trong protocol viết khai báo hàm và được định nghĩa bên trong class gọi.

Cách tạo delegate?

Làm với ví dụ dự án.

Các bước thực hiện:

  • Tạo class FirstViewController, tạo class khác SecondViewController. Tạo view controller tương ứng trong storyboard.
  • Khai báo protocol trong SecondViewController, protocol khai báo bên ngoài class hoặc đối tượng khác.
protocol SecondViewControllerDelegate {    func buttonPressedInVC2() }
  • Trong SecondViewController, tạo đối tượng tùy chọn (optional) của delegate vừa tạo:
var delegate: SecondViewControllerDelegate?
  • Cần gọi hàm khai báo trong protocol khi sự kiện xảy ra trong SecondViewController, tạo sự kiện khi nút bấm được nhấn trong second view controller.
@IBAction func buttonTapped(_ sender: UIButton) {    self.delegate?.buttonPressedInVC2()    self.navigationController?.popViewController(animated: true) }

Xong phần SecondViewController, làm việc trên FirstViewController.

  • Cần conform/implement FirstViewController vào SecondViewControllerDelegate, Xcode sẽ tự yêu cầu thêm protocol stubs.
extension FirstViewController: SecondViewControllerDelegate {    func buttonPressedInVC2() { } }
  • Bên trong protocol vừa implement, viết code muốn thực thi khi delegate action xảy ra. Tạo label trong FirstViewController và thay đổi text khi delegate method được gọi.
extension FirstViewController: SecondViewControllerDelegate {    func buttonPressedInVC2() {       self.lblOne.text = "Delegate Implemented"    } }
  • Bước cuối: delegate object trong SecondViewController là optional và nil cho đến khi gán. Trong FirstViewController, gán object đó khi chuyển từ FirstViewController sang SecondViewController. Tạo nút trong FirstViewController cho việc đó.
@IBAction func goToNextVC(_ sender: Any) {    let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController    vc.delegate = self    self.navigationController?.pushViewController(vc, animated: true) }
  • Nhớ nhúng FirstViewController trong Navigation Controller. Chạy app xem kết quả.

Thiết lập delegate đơn giản để giao tiếp giữa hai view controller trong iPhone