我的根viewController包含另一个类的变量和一个显示该类视图的按钮:
class ViewController: UIViewController {
var myBoxView = BoxView()
override func viewDidLoad() {
let btn = UIButton()
btn.backgroundColor = UIColor.green
btn.addTarget(self, action: #selector(showBoxView), for: .touchUpInside)
view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: btn, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: btn, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.5, constant: 0))
}
}
extension ViewController {
@objc func showBoxView(_ sender: UITapGestureRecognizer?) {
// let myBoxView = BoxView()
myBoxView.showView()
}
}
另一个类符合NSObject并具有另一个按钮来关闭其视图:
class BoxView: NSObject {
let boxView = UIView(frame: CGRect(x: 50, y: 200, width: 300, height: 300))
let closeBtn = UIButton()
func showView() {
if let window = UIApplication.shared.keyWindow {
closeBtn.addTarget(self, action: #selector(closeBoxView), for: .touchUpInside)
closeBtn.backgroundColor = UIColor.blue
closeBtn.translatesAutoresizingMaskIntoConstraints = false
boxView.addSubview(closeBtn)
boxView.addConstraint(NSLayoutConstraint(item: boxView, attribute: .centerX, relatedBy: .equal, toItem: closeBtn, attribute: .centerX, multiplier: 1, constant: 0))
boxView.addConstraint(NSLayoutConstraint(item: boxView, attribute: .centerY, relatedBy: .equal, toItem: closeBtn, attribute: .centerY, multiplier: 1, constant: 0))
boxView.backgroundColor = UIColor.red
window.addSubview(boxView)
boxView.alpha = 1
}
}
}
extension BoxView {
@objc func closeBoxView(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.3) {
self.boxView.alpha = 0
self.boxView.removeFromSuperview()
}
}
}
代码已简化。
一切正常,直到 ... (即,当一个人按下根按钮时,将触发选择器(showBoxView)并显示BoxView。然后,一个人按下关闭按钮(closeBoxView将被激发,然后淡出。然后恢复正常操作。)
当我不使用全局变量(myBoxView)并创建新实例时,该类的“关闭”按钮的选择器(closeBoxView)将不会触发。即使显示了boxView。
(即,我将let myBoxView = BoxView()
插入“ showBoxView”方法的顶部)
为什么不使用选择器(closeBoxView)而不使用其实例(从根VC)呢?
PS。我通过添加AppDelegate“ didFinishLaunchingWithOptions”,以编程方式完成了此操作:
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = ViewController()