触摸处理程序上的 SKNode

问题描述

有没有办法在 SKNode 上“注入”触摸处理程序? SKNode 能够通过 touchesBegun/Moved/Ended/Cancelled 方法和 isUserInteractionEnabled 标志属性接收触摸事件,但是需要子类化以提供自定义功能。委托或块注入可以很好地专门化这种行为,例如:

let myNode : SKNode = someFunctionReturningAnSKNode()
myNode.onTouchesBeganHandler = { touches in
   // my specialized code would go here
}

我认为另一种方法是在此节点之上添加自己的节点并模仿其大小并覆盖 touches 方法,但这很丑陋,并且如果底层节点更改大小则难以匹配准确性。

作为替代,我编写了这个解决方案,这是一种解决方法:

class SKTouchNode : SKNode {
    
    enum TouchesCondition {
        case began,moved,ended,cancelled
    }
    
    typealias Handler = (_ condition: TouchesCondition,_ touches: Set<UITouch>,_ event: UIEvent?)->Void
    
    init(handler: Handler? = nil) {
        super.init()
        isUserInteractionEnabled = true
        self.handler = handler
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var handler : Handler?
    
    override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
        handler?(.began,touches,event)
    }
    override func touchesMoved(_ touches: Set<UITouch>,with event: UIEvent?) {
        handler?(.moved,event)
    }
    override func touchesEnded(_ touches: Set<UITouch>,with event: UIEvent?) {
        handler?(.ended,event)
    }
    override func touchesCancelled(_ touches: Set<UITouch>,with event: UIEvent?) {
        handler?(.cancelled,event)
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...