0

我有一个 UIViewController、一个 Custum UIView 和一个 GameController。CustumUiView 位于 UIViewController 之上,我需要分离视图以跟踪 UIView 上的点击。我在 Custum UIView“界面视图”中有一个自定义按钮正在注册点击,但 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")
}
4

1 回答 1

0

通过在 GameViewController 中解决,使用 didSet 设置按钮按下的目标和选择器,然后使用 GameViewController 中的方法调用 GameController 中的方法。

@IBOutlet weak var interface: InterfaceView!
{
    didSet
    {
        interface.resetButton.addTarget(self, action: #selector (GameViewController.reset), for: .touchUpInside)
    }
}
于 2016-10-20T19:06:20.000 回答