简体   繁体   English

可以在NSObject类的UIButton中添加Target吗?

[英]Can you addTarget to UIButton in NSObject class?

How do you addTarget to a UIButton in an NSObject class? 如何在NSObject类的UIButton中添加Target? 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. NSObject不会从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? 也许您可以使UIButton具有NSObject类型的属性来携带一些附带信息?

Look at the UIControl API 看一下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. 通常,您会在界面生成器中添加一个按钮,并从UIViewController之类的某些控制器类中对该按钮添加引用(IBOutlet)。

edit 编辑

Ah, now I see the problem. 嗯,现在我明白了。 Don't use Selector in swift. 不要迅速使用选择器。 This should work. 这应该工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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