我无法弄清楚为什么我的点按手势不起作用。黑色取消窗口显示正常,但是当我点击黑色窗口时,都没有调用handleCancel()函数。
import UIKit
protocol BlackCancelWindowDelegate {
func handleCancel()
}
class BlackCancelWindow: NSObject {
let blackView = UIView()
var delegate: BlackCancelWindowDelegate?
var frame: CGRect?
override init() {
super.init()
}
func showCancelWindow() {
if let window = UIApplication.shared.keyWindow {
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
blackView.frame = frame ?? window.frame
blackView.alpha = 0
window.addSubview(blackView)
let tapToDismiss = UITapGestureRecognizer(target: self, action: #selector(handleCancel))
tapToDismiss.numberOfTapsRequired = 1
blackView.addGestureRecognizer(tapToDismiss)
UIView.animate(withDuration: 0.5,animations: {
self.blackView.alpha = 1
}, completion: nil)
}
}
func handleCancel() {
print("BlackCancelWindow cancel")
UIView.animate(withDuration: 0.5, animations: {
self.blackView.alpha = 0
}, completion: nil)
delegate?.handleCancel()
}
}
class ViewController: UIViewController, BlackCancelWindowDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func showCancelWindow(_ sender: Any) {
let cancelWindow = BlackCancelWindow()
cancelWindow.delegate = self
cancelWindow.showCancelWindow()
}
func handleCancel() {
print("Delegate cancel")
}
}
答案 0 :(得分:1)
不确定为什么会这样,而我之前的代码却没有,但诀窍是将UIView子类化为NSObject。像这样......
import UIKit
protocol BlackCancelViewDelegate {
func handleCancel()
}
class BlackCancelView: UIView {
var delegate: BlackCancelViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0, alpha: 0.5)
}
convenience init() {
if let window = UIApplication.shared.keyWindow {
self.init(frame: window.frame)
} else {
self.init()
}
}
func showCancelWindow() {
if let window = UIApplication.shared.keyWindow {
alpha = 0
window.addSubview(self)
let tapToDismiss = UITapGestureRecognizer(target: self, action: #selector(handleCancel))
addGestureRecognizer(tapToDismiss)
UIView.animate(withDuration: 0.5,animations: {
self.alpha = 1
}, completion: nil)
}
}
func handleCancel() {
print("BlackCancelView cancel")
UIView.animate(withDuration: 0.5,animations: {
self.alpha = 0
}, completion: nil)
delegate?.handleCancel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController, BlackCancelViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func showCancelWindow(_ sender: Any) {
let cancel = BlackCancelView()
cancel.delegate = self
cancel.showCancelWindow()
}
func handleCancel() {
print("Delegate cancel")
}
}
我不确定我是否以正确的方式执行了这些初始化函数。如果有更好的方法,请告诉我。