[SWIFT] Cách tạo Popup View sử dụng View Controller riêng biệt

Tram Ho

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:

Trong PopupViewVC, ta tạo hàm thực thi việc ẩn Popup View:

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:

Trong MainViewController, ta sẽ gán giá trị lấy được bên PopupView vào nameLabel

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

Link github:

https://github.com/huybnd-1816/PopupViewSample

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo