首页 > 解决方案 > 在 KeyWindow 上将 XIB 显示为 UIView

问题描述

我在 KeyWindow 上显示一个 Xib 作为我的自定义警报视图。

我遇到的问题是,当我再次呈现视图时(从超级视图中删除它之后),具有目标的按钮仍然具有分配给它们的旧操作。所以当一个按钮被点击时,它会执行它的新动作和旧动作。

除了将代码设置为 .removeTarget(nil, action: nil, for: .allEvents) 从按钮。当视图被添加到子视图新时间时,为什么按钮没有呈现新鲜?

应用程序委托中的代码:

let AlertScreen = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert

    func ShowAlert (LeftButton: String, RightButton: String) {

        AlertScreen.frame = UIScreen.main.bounds
        AlertScreen.LeftButton.setTitle(LeftButton, for: .normal)
        AlertScreen.RightButton.setTitle(RightButton, for: .normal)
        UIApplication.shared.keyWindow?.addSubview(AlertScreen)

    }

然后在我需要显示警报视图的任何视图控制器中,我只需显示警报,然后分配一个操作,例如:

AlertScreen.RightButton.addTarget(self, action: #selector(LoadItems), for: .touchUpInside)

标签: swift

解决方案


您只需使用以下方法创建一次视图:

let AlertScreen = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert

您一遍又一遍地呈现保存视图。如果您想要新鲜的视图,您需要在每次呈现时创建一个新视图。

var currentAlert: Alert?

func showAlert (LeftButton: String, RightButton: String) {

    removeAlert()
    currentAlert = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert
    currentAlert.frame = UIScreen.main.bounds
    currentAlert.LeftButton.setTitle(LeftButton, for: .normal)
    currentAlert.RightButton.setTitle(RightButton, for: .normal)
    UIApplication.shared.keyWindow?.addSubview(currentAlert)

}

func removeAlert() {
    currentAlert?.removeFromSuperView()
    currentAlert = nil
}

推荐阅读