首页 > 解决方案 > Swift:视图控制器触摸事件中的自定义 UIButton 类未触发?

问题描述

我这样创建了一个自定义UIButton类:

class CustomButton: UIButton
{
    required init(frame: CGRect, title: String, alignment: NSTextAlignment)
    {
        super.init(frame: frame)

        // Set properties

//        self.addTarget(self,
//                       action: #selector(touchCancel),
//                       for: .touchUpInside)
    }

    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }

//    @objc fileprivate func touchCancel()
//    {
//        print("TOUCHED")
//    }
}

在我的 mainUIViewController中,我有以下实现:

class MainViewController: UIViewController
{   
    fileprivate var customBtn: CustomButton {
        let frame = CGRect(x: 48.0,
                           y: 177.0,
                           width: 80.0,
                           height: 40.0)
        let custom = CustomButton(frame: frame,
                                  title: "Test",
                                  alignment: NSTextAlignment.right)
        return custom
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        view.addSubView(customBtn)

        customBtn.addTarget(self,
                            action: #selector(touchCancel),
                            for: .touchUpInside)
    }

    @objc public func touchCancel()
    {
        print("TOUCHED")
    }
}

但是,customBtn在我的主目录中添加目标UIViewController不会被触发。CustomButton如带有注释掉代码的类中所示,我可以在那里添加一个目标,它确实会被触发。

我只是想知道为什么不能使用另一个类中定义的函数作为目标添加到自定义UIButton?....或者我的实现不正确?

谢谢!

标签: iosswiftuibutton

解决方案


您可能需要一个闭包而不是计算属性

lazy var customBtn: CustomButton = {
    let frame = CGRect(x: 48.0, y: 177.0, width: 80.0, height: 40.0)
    let custom = CustomButton(frame: frame, title: "Test",alignment: NSTextAlignment.right)
    return custom
}()

这里里面MainViewController

customBtn.addTarget(self,
                        action: #selector(touchCancel),
                        for: .touchUpInside)

您将目标添加到新创建的实例而不是添加为子视图的实例,这是您的实现(计算属性)和闭包之间的主要区别


推荐阅读