在ViewController中显示弹出窗口可以通过以下步骤实现:
以下是一个示例代码,演示如何在ViewController中显示弹出窗口:
// 弹出窗口的视图控制器
class PopupViewController: UIViewController {
// 弹出窗口的内容视图
let popupView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// 设置弹出窗口的样式和大小
popupView.backgroundColor = .white
popupView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
popupView.center = view.center
// 添加关闭按钮
let closeButton = UIButton(type: .system)
closeButton.setTitle("关闭", for: .normal)
closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
closeButton.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
closeButton.center = CGPoint(x: popupView.bounds.width / 2, y: popupView.bounds.height - 40)
popupView.addSubview(closeButton)
// 将弹出窗口的视图添加到当前视图控制器的视图层级中
view.addSubview(popupView)
}
@objc func closeButtonTapped() {
// 关闭弹出窗口
dismiss(animated: true, completion: nil)
}
}
// 在ViewController中显示弹出窗口
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 添加一个按钮,点击时显示弹出窗口
let showPopupButton = UIButton(type: .system)
showPopupButton.setTitle("显示弹出窗口", for: .normal)
showPopupButton.addTarget(self, action: #selector(showPopupButtonTapped), for: .touchUpInside)
showPopupButton.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
showPopupButton.center = view.center
view.addSubview(showPopupButton)
}
@objc func showPopupButtonTapped() {
// 实例化并显示弹出窗口的视图控制器
let popupViewController = PopupViewController()
popupViewController.modalPresentationStyle = .overCurrentContext
present(popupViewController, animated: true, completion: nil)
}
}
这是一个简单的示例,你可以根据实际需求进行修改和扩展。在实际开发中,你可以使用第三方库或者自定义视图来实现更复杂的弹出窗口效果。
领取专属 10元无门槛券
手把手带您无忧上云