我有一个UIViewController,一个Custum UIView和一个GameController。 CustumUiView位于UIViewController之上,我需要分离视图以跟踪UIView上的点击。我在Custum UIView" Interface View"中有一个自定义按钮。注册点击,但GameController中的接收器或UIViewController(两者都试过)都没有注册点击。
代码如下,感谢您的帮助。
界面视图
class InterfaceView: UIView {
var resetButton: UIButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
resetButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
resetButton.setImage(UIImage(named: "reset"), for: UIControlState())
addSubview(resetButton)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// let touches through and only catch the ones on buttons
let hitView = super.hitTest(point, with: event)
if hitView is UIButton {
print("Captured Hit") // Stack Overflow Note: This is working.
return hitView
}
return nil
}
}
游戏控制器:
class GameController
{
var interface: InterfaceView!
{
didSet
{
interface.resetButton.addTarget(self, action: #selector (GameController.reset), for: .touchUpInside)
}
@objc func reset(sender: UIButton!)
{
print("button pressed")
}
}
的UIViewController:
class GameViewController: UIViewController
{
fileprivate let controller: GameController
@IBOutlet weak var GameView: UIView!
init(_ coder: NSCoder? = nil)
{
// Logic Goes Here
controller = GameController()
if let coder = coder
{
super.init(coder: coder)!
} else
{
super.init(nibName: nil, bundle: nil)
}
}
required convenience init(coder: NSCoder)
{
self.init(coder)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first as UITouch?
{
let point = touch.preciseLocation(in: GameView)
if (touch.view == GameView)
{
print("Do stuff")
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first
{
let point = touch.preciseLocation(in: GameView)
if (touch.view == GameView)
{
print("Do other stuff")
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
print("Reset Stuff")
}
答案 0 :(得分:0)
Resolved by in GameViewController, using didSet to set the target and selector for the button press and then using a method in GameViewController to call a method within GameController.
@IBOutlet weak var interface: InterfaceView!
{
didSet
{
interface.resetButton.addTarget(self, action: #selector (GameViewController.reset), for: .touchUpInside)
}
}