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

标签 ios swift uiview

我有一个 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())
    }

It's added successfully

// 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/

相关文章:

swift - 加载启动 URL 失败,错误为 : Error Domain=TVMLKitErrorDomain Code=3 "(null)"

swift - 符合 Decodable 的类不需要初始化器

iOS登录/自动登录和注销流程

ios - 如何根据父 View 调整 subview 的大小和位置?

iphone - 缩放基于 View 的 iOS 应用程序的页面

android - 在 Chromecast 上播放 Widevine DRM

javascript - 想要一个 100% 宽度/高度的 iPhone/iPad/iOS 网页

ios - Monotouch自定义UIView

ios - 基于 nil 变量不返回任何单元格

objective-c - 指定初始化器并调用它