swift - 在 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)
解决方案
您只需使用以下方法创建一次视图:
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
}
推荐阅读
- r - 实施严格的重载方法签名以防止误用
- reactjs - 从 Redux 迁移到 React Context API + hooks 时如何处理副作用
- jquery - 在数据表列复选框下拉列表中使用可选择的 jQuery
- json - 将一组表单输入转换为 JSON
- excel - VBA ExportAsFixedFormat to PDF 不打印某些图像
- css - 最佳实践:在背景上绘制形状
- html - 为什么 Chrome 和 Safari 的尺寸不同(媒体查询问题)
- reactjs - 为图像添加价值 React Native
- python - 如何扩展列表以处理诸如“38359*0”之类的元素,我想将其表示为等于 0 的 38359 个元素?
- websphere - 如何从 Websphere Portal 服务器获取 HTML url?