gpt4 book ai didi

swift - 自定义按钮在 Swift 中不起作用

转载 作者:行者123 更新时间:2023-11-30 12:58:16 25 4
gpt4 key购买 nike

我有一个 UIViewController、一个 Custum UIView 和一个 GameController。 CustumUiView 位于 UIViewController 之上,我需要分离 View 来跟踪 UIView 上的点击。我在 Custum UIView“界面 View ”中有一个正在注册点击的自定义按钮,但 GameController 或 UIViewController 中的接收器(都尝试过)没有注册点击。

代码如下,感谢帮助。

界面 View

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
}
}

游戏 Controller :

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")
}

最佳答案

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

@IBOutlet weak var interface: InterfaceView!
{
didSet
{
interface.resetButton.addTarget(self, action: #selector (GameViewController.reset), for: .touchUpInside)
}
}

关于swift - 自定义按钮在 Swift 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40161950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com