试图在 super class 中分配按钮的目标

Trying to assign the target of a button in the super class

我有一个 baseVc,我的所有 UIViewController 都继承自它,所有这些都将在 UINavigationBar 中具有相同的按钮,如果它们嵌入在 UINavigationController 中。

我想做的是从 child class 设置这些按钮之一的目标和操作,但我没有运气。我怎样才能让它工作?

@interface BaseVc : UIViewController  
@property (strong,nonatomic) UIBarButtonItem *actionButton;  

@end

上面是我的parentclass的header,在childclass:

[[super actionButton] setTarget:self];
[[super actionButton] setAction:@selector(viewMenu)];

如果我没理解错的话,你接下来应该做的是:将操作分配给父级 class 中的按钮,例如 -doRightMenuButtonAction,然后在子级 class 中重写此方法并处理这个动作。

由于您的子类继承自BaseVC,它可以访问actionButton 属性。所以我试试看:

[self.actionButton setTarget:self];
[self.actionButton setAction:@selector(viewMenu)];

确保您没有将按钮标记为私有。

class BaseViewController: UIViewController {

    var button  = UIButton.buttonWithType(UIButtonType.System) as UIButton

    override func viewDidLoad() {
        super.viewDidLoad()
        button.frame  = CGRectMake(20, 200, 200, 44)
        button.setTitle("Hello World", forState: .Normal)
        self.view.addSubview(button)
    }
}

然后在你的子类中...

    class AceViewController: BaseViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            button.addTarget(self, action: "sayHello:", forControlEvents: .TouchUpInside)
        }

        func sayHello (button: UIButton) {
            UIAlertView(title: "Hello", message: "World", delegate: nil, cancelButtonTitle: "Ok").show()
        }
}