我的自定义UIView未从SuperView中删除

iHa*_*hil 3 uiview ios swift

我有一个PopUpView,我添加到ViewController.

我创建了一个委托方法didTapOnOKPopUp(),这样当我点击PopUpView中的Ok Button时,它应该从使用它的委托的ViewController中删除.

这是PopUpView.Swift的代码

protocol PopUpViewDelegate: class {
    func didTapOnOKPopUp()
}


class PopUpView: UIView {
weak var delegate : PopUpViewDelegate?

@IBAction func btnOkPopUpTap(_ sender: UIButton)
    {
        delegate?.didTapOnOKPopUp()
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我使用委托方法的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())
    }
Run Code Online (Sandbox Code Playgroud)

它已成功添加

// But when I tapping on OK Button. My PopUpView is not removing from it's View Controller. 

func didTapOnOKPopUp() {

        self.popUpInstance().removeFromSuperview()
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过这个但没有成功!请帮我.谢谢!

CZ5*_*Z54 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
}
Run Code Online (Sandbox Code Playgroud)

但我认为在你的情况下使用a 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
    }
Run Code Online (Sandbox Code Playgroud)

通过:

lazy var popUpInstance : UIView =  {
        let popUpView = UINib(nibName: "PopUpView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! PopUpView
        popUpView.delegate = self
        return popUpView
    }()
Run Code Online (Sandbox Code Playgroud)

现在每次调用都popUpInstance将返回popUp的相同实例