简体   繁体   中英

Can you addTarget to UIButton in NSObject class?

How do you addTarget to a UIButton in an NSObject class? Or will that class not work?

class Support: NSObject {

    func helpButton(viewController: ProfileVC) {

    let helpButton = viewController.helpButton
    helpButton.frame.size = CGSizeMake(35.0, 35.0)
    helpButton.layer.cornerRadius = helpButton.frame.height/2
    helpButton.layer.borderWidth = 0.5
    helpButton.layer.borderColor = lightColoredFont.CGColor
    helpButton.setTitle("?", forState: .Normal)
    helpButton.setTitleColor(lightColoredFont, forState: .Normal)
    helpButton.titleLabel?.font = fontSmaller
    helpButton.addTarget(self, action: Selector("showOptions"), forControlEvents: .TouchUpInside)
    helpButton.center.y = viewController.logoutButton.center.y
    helpButton.frame.origin.x = (viewController.view.bounds.width - viewController.logoutButton.frame.maxX)
    viewController.view.addSubview(helpButton)

    }

    func showOptions() {

        print("showing")

    }

}

The print is not showing. Even if I feed an instantiated support class into the target for the button it will not work. What is the proper way to do this?

In short, no.

NSObject does not inherit from anything in UIKit. Your inheritance should be the other way around. Perhaps you could make a UIButton that has a property of type NSObject to carry some accompanying information?

Look at the UIControl API

func addTarget(_ target: AnyObject?, action action: Selector, forControlEvents controlEvents: UIControlEvents)

But what are you trying to do? Normally you would add a button in interface builder and a reference (IBOutlet) to that button from some controller class like UIViewController.

edit

Ah, now I see the problem. Don't use Selector in swift. This should work.

helpButton.addTarget(self, action: "showOptions", forControlEvents: .TouchUpInside)

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