你可以在NSObject类中添加Target到UIButton吗?
你怎么addTarget到一个NSObject类的UIButton? 还是那个class不行?
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") } }
打印没有显示。 即使我提供一个实例化的支持类到button的目标,它将无法正常工作。 什么是正确的方法来做到这一点?
总之,没有。
NSObject
不会从UIKit中的任何东西inheritance。 你的inheritance应该是相反的。 也许你可以做一个具有NSObject
types属性的UIButton
来携带一些伴随的信息?
看看UIControl API
func addTarget(_ target: AnyObject?, action action: Selector, forControlEvents controlEvents: UIControlEvents)
但是你想做什么? 通常你会在界面构build器中添加一个button,并从像UIViewController这样的控制器类中为该button添加一个引用(IBOutlet)。
编辑
啊,现在我看到了这个问题。 不要在swift中使用Selector。 这应该工作。
helpButton.addTarget(self, action: "showOptions", forControlEvents: .TouchUpInside)