有没有可能子类UIEvent来嵌入一些额外的信息?我试过了,但是一直得到异常,并且找不到任何关于UIEvent子类化的东西。
class CustomEvent: UIEvent {
let payload: CustomData
override init(payload: CustomData) {
super.init()
self.payload = payload
}
}
017-03-30 08:51:17.504497 StealingTouches[1041:778674] -[StealingTouches.TouchEvent _firstTouchForView:]: unrecognized selector sent to instance 0x170053950
2017-03-30 08:51:17.505470 StealingTouches[1041:778674] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[StealingTouches.TouchEvent _firstTouchForView:]: unrecognized selector sent to instance 0x170053950'
*** First throw call stack:
(0x18bf991b8 0x18a9d055c 0x18bfa0268 0x18bf9d270 0x18be9680c 0x191e8494c 0x100026278 0x100026550 0x100026fc4 0x100027214 0x191e7be98 0x191e77328 0x191e47da0 0x19263175c 0x19262b130 0x18bf46b5c 0x18bf464a4 0x18bf440a4 0x18be722b8 0x18d926198 0x191eb27fc 0x191ead534 0x100029418 0x18ae555b8)
libc++abi.dylib: terminating with uncaught exception of type NSException我有一个视图集合嵌套在超级视图中的3个层次。我希望深度嵌套的视图将一些自定义数据添加到事件中,并将这些数据向上转发到最外层的视图。
请参见图像。绿色视图应该处理事件,执行适当的计算,将数据保存到事件中,并将数据向上转发到红色视图。只有绿色视图响应事件,但只有红色视图知道如何处理该事件。

绿色的视图处理触摸..。
class GreenView: UIControl {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
//do some complicated calculation then save in custom event
let customEvent = CustomEvent.init(payload: calculations)
if let nextRespoonder = self.next {
nextRespoonder.touchesBegan(touches, with: customEvent)
}
}
}然后被转发到黄色视图。
class YellowView: UIControl {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let nextRespoonder = self.next {
nextRespoonder.touchesBegan(touches, with: event)
}
}
}最后,红色视图可以提取事件有效负载并执行它需要做的事情……
class RedView: UIControl {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let customEvent = event as? CustomEvent {
let payload = customEvent.payload
//do something with the payload
}
}
}另一种选择是将有效负载数据本地存储在绿色视图中,然后红色视图需要做的唯一一件事就是识别哪个绿色视图启动了事件。这对于点击测试来说是相当简单的,但我有超过100个这样的绿色视图,并且它可能会变得相当复杂,因为有时绿色视图会重叠在一起,从而确定哪一个是仅基于点击测试的。
发布于 2017-03-31 01:36:04
我认识到这种模式是错误的处理方式。更好的做法是使用委托。分配redView作为greenView的代表,只需传递信息即可。
protocol GreenViewDelegate {
func onTouchesBegan(greenView: GreenView)
}
class GreenView: UIControl {
var delegate: GreenViewDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.delegate?.onTouchesBegan(greenView: self)
}
}
class RedView: UIControl, GreenViewDelegate {
init() {
greenView.delegate = self
}
func onTochesBegan(greenView: GreenView) {
//extract whatever data you want
}
}https://stackoverflow.com/questions/43123899
复制相似问题