我正在尝试UITouch
通过创建UIResponder
扩展来调整生命周期事件。以下是描述touchesBegan
.
public extension UIResponder {
private enum TouchPhase: String {
case begin
case move
case end
case cancel
//computed property
var phase: String {
return self.rawValue
}
}
@objc func swizztouchesBegan(_ touches: Set<UITouch>, with event:
UIEvent?) {
print("swizztouchesBegan event called!")
let touch = touches.first! as UITouch
self.createTouchesDict(for: touch, event: event, phase: .begin)
self.swizztouchesBegan(touches, with: event)
}
static func swizzleTouchesBegan() {
let _: () = {
let originalSelector =
#selector(UIResponder.touchesBegan(_:with:))
let swizzledSelector =
#selector(UIResponder.swizztouchesBegan(_:with:))
let originalMethod = class_getInstanceMethod(UIResponder.self, originalSelector)
let swizzledMethod = class_getInstanceMethod(UIResponder.self, swizzledSelector)
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}()
}
}
然后我像这样在我的应用程序中调用它-
[UIResponder swizzleTouchesBegan]; //my app is a mix of Objective-C and Swift
我看到的是-“调用了 swizztouchesBegan 事件!” 被打印出来,我开始创建触摸元数据的字典。但是,它看起来并没有调用原始实现,例如,假设在我的代码中的某个地方,在表格视图控制器中,我编写了以下内容 -
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
print("AM I GETTING CALLED?")
}
这个被覆盖的 touchesBegan 没有被调用 - 可能是什么问题?我已经通过再次调用 swizzled 来从 swizzled 内部调用原始实现(从而确保调用原始实现。)
PS/附录:我已经能够通过覆盖UIView
扩展中的触摸方法来使其工作,如下所示。有人可以指出使用这种方法比使用这种方法有什么缺点吗?
public extension UIView {
private enum TouchPhase: String {
case begin
case move
case end
case cancel
//computed property
var phase: String {
return self.rawValue
}
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("overriding touches began event!")
let touch = touches.first! as UITouch
self.createTouchesDict(for: touch, event: event, phase: .begin)
super.touchesBegan(touches, with: event)
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
print("overriding touches moved event!")
let touch = touches.first! as UITouch
self.createTouchesDict(for: touch, event: event, phase: .move)
super.touchesMoved(touches, with: event)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("overriding touches ended event!")
let touch = touches.first! as UITouch
self.createTouchesDict(for: touch, event: event, phase: .end)
super.touchesEnded(touches, with: event)
}
open override func touchesCancelled(_ touches: Set<UITouch>, with
event: UIEvent?) {
print("overriding touches canceled event!")
let touch = touches.first! as UITouch
self.createTouchesDict(for: touch, event: event, phase: .cancel)
super.touchesCancelled(touches, with: event)
}
}