简体   繁体   中英

Swift: Custom UIButton Class in View Controller Touch Event Not Trigger?

I created a custom UIButton class as so:

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

In my main UIViewController , I have the following implementation:

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

However, adding a target to customBtn in my main UIViewController does not get triggered. As shown in the CustomButton class with the commented out code, I can add a target there, which does get triggered.

I'm just wondering why a defined function in another class cannot be used to add as a target to a custom UIButton ?....or maybe my implementation is incorrect?

Thanks!

You may need a closure not a computed property

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

Here inside MainViewController

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

you add the target to a newly created instance not to the one you added as a subview and it's the main difference between your implementation ( computed property ) and closure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM