我有一个 PopUpView,我将其添加到 ViewController。
我已经创建了一个委托(delegate)方法 didTapOnOKPopUp(),这样当我在 PopUpView 中单击“确定”按钮时,它应该从使用它的委托(delegate)的 ViewController 中删除。
这是 PopUpView.Swift 的代码
protocol PopUpViewDelegate: class {
func didTapOnOKPopUp()
}
class PopUpView: UIView {
weak var delegate : PopUpViewDelegate?
@IBAction func btnOkPopUpTap(_ sender: UIButton)
{
delegate?.didTapOnOKPopUp()
}
}
这是我使用委托(delegate)方法的 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但没有成功!请帮我。谢谢!
最佳答案
每次调用 popupinstance()
都会创建一个新的 PopUp
View 。
您可以创建对创建的弹出窗口的引用:
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
都会返回相同的 popUp 实例
关于ios - 我的自定义 UIView 未从 SuperView 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150166/