我有一个 PopUpView ,我将其添加到 ViewController 。
我创建了一个委托方法 didTapOnOKPopUp(),以便当我在PopUpView中单击“确定”按钮时,应从使用它的委托的ViewController中删除。
这是 PopUpView.Swift
的代码protocol PopUpViewDelegate: class {
func didTapOnOKPopUp()
}
class PopUpView: UIView {
weak var delegate : PopUpViewDelegate?
@IBAction func btnOkPopUpTap(_ sender: UIButton)
{
delegate?.didTapOnOKPopUp()
}
}
这是我正在使用委托方法的 ForgotPasswordViewController 的代码。
class ForgotPasswordViewController: UIViewController, PopUpViewDelegate {
// I have created an Instance for the PopUpView and assign Delegate also.
func popUpInstance() -> UIView {
let popUpView = UINib(nibName: "PopUpView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! PopUpView
popUpView.delegate = self
return popUpView
}
// Here I am adding my view as Subview. It's added successfully.
@IBAction func btnSendTap(_ sender: UIButton) {
self.view.addSubview(self.popUpInstance())
}
// But when I tapping on OK Button. My PopUpView is not removing from it's View Controller.
func didTapOnOKPopUp() {
self.popUpInstance().removeFromSuperview()
}
}
我尝试了this,但没有成功!请帮我。谢谢!
答案 0 :(得分:5)
每次调用popupinstance()
都会创建一个新的PopUp
视图。
您可以创建对创建的弹出窗口的引用:
private var displayedPopUp: UIView?
@IBAction func btnSendTap(_ sender: UIButton) {
displayedPopUp = self.popUpInstance()
self.view.addSubview(displayedPopUp)
}
func didTapOnOKPopUp() {
self.displayedPopUp?.removeFromSuperview()
displayedPopUp = nil
}
但我认为在您的情况下,使用lazy var
更好:
替换
func popUpInstance() -> UIView {
let popUpView = UINib(nibName: "PopUpView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! PopUpView
popUpView.delegate = self
return popUpView
}
作者:
lazy var popUpInstance : UIView = {
let popUpView = UINib(nibName: "PopUpView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! PopUpView
popUpView.delegate = self
return popUpView
}()
现在,每次调用popUpInstance
都将返回弹出窗口的相同实例
答案 1 :(得分:3)
每次调用.popUpInstance()
时,它都会创建一个全新的PopupView
实例,从而使您失去对先前在视图层次结构中创建并添加的实例的引用。
将popUpView
定义为实例变量,您应该会很好:
class ForgotPasswordViewController: UIViewController, PopUpViewDelegate {
private lazy var popupView: PopUpView = {
let popUpView = UINib(nibName: "PopUpView", bundle: nil)
.instantiate(withOwner: nil, options: nil)
.first as! PopUpView
popUpView.delegate = self
return popUpView
}()
@IBAction func btnSendTap(_ sender: UIButton) {
self.view.addSubview(self.popupView)
}
func didTapOnOKPopUp() {
self.popupView.removeFromSuperview()
}
}
答案 2 :(得分:0)
每次调用函数popUpInstance时,都会创建另一个PopUpView实例,当您这样做时,您的委托就不相关了。
您可以通过某些方式来完成这部分代码:
创建popUpInstance()函数并将实例另存为类参数
创建这样的类参数
dy