Môi trường phát triển:
- Swift Language Version: Swift 5
- Xcode: Version 10.2.1 (10E1001)
- Deployment Target: 11.0
Bước 1: Tạo giao diện cho Popup View trong main.storyboard
Trong ví dụ này, ta sẽ tạo một giao diện đơn giản được bố trí như hình dưới đây:
Trong đó, Popup View được set constraint như sau:
- Leading Constraint: 64
- CenterX Constraint: safe Area
- CenterY Constraint: safe Area
- Width Constraint = Height Constraint
Tiếp theo, ta set backgroundColor cho Popup View: black color với opacity = 0.5
Đây là giao diện cuối cùng sau khi ta thiết lập:
Bước 2: Xử lý ẩn hiện Popup View
Trong MainViewController, ta sẽ tạo nút Open PopupView và hàm thực thi để hiển thị Popup View:
1 2 3 4 5 6 7 | @IBAction func handleOpenButtonTapped(_ sender: Any) { guard let vc = storyboard?.instantiateViewController(withIdentifier: "PopupViewVC") else { return } vc.modalPresentationStyle = .overFullScreen vc.modalTransitionStyle = .crossDissolve present(vc, animated: true) } |
Trong PopupViewVC, ta tạo hàm thực thi việc ẩn Popup View:
1 2 3 4 | @IBAction func handleCloseButtonTapped(_ sender: Any) { dismiss(animated: true) } |
Bước 3: Truyền dữ liệu từ PopupView đến MainView
Trong PopupViewVC, ta tạo một closure didSendData để truyền dữ liệu lấy từ textField đến MainViewController:
1 2 3 4 5 6 7 8 9 | var didSendData: ((String) -> Void)? @IBAction func handleCloseButtonTapped(_ sender: Any) { if let name = nameTextField.text { didSendData?(name) } dismiss(animated: true) } |
Trong MainViewController, ta sẽ gán giá trị lấy được bên PopupView vào nameLabel
1 2 3 4 5 6 7 8 9 10 11 12 | @IBAction func handleOpenButtonTapped(_ sender: Any) { guard let vc = storyboard?.instantiateViewController(withIdentifier: "PopupViewVC") as? PopupViewVC else { return } vc.modalPresentationStyle = .overFullScreen vc.modalTransitionStyle = .crossDissolve present(vc, animated: true) vc.didSendData = { [weak self] name in guard let self = self else { return } self.nameLabel.text = name } } |
Và đây là kết quả cuối cùng:
Tài liệu tham khảo:
https://www.youtube.com/watch?v=NBCped0ZcWE&vl=en