通过KeyWindow将XIB作为UIView呈现并删除

时间:2018-08-08 23:42:26

标签: swift

我正在将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)

1 个答案:

答案 0 :(得分:0)

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

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
}