简体   繁体   English

自定义UIButton类,对不同的ViewControllers具有相同的操作

[英]Custom UIButton class with same action for different ViewControllers

I've seen a lot of examples of creating buttons programmatically in ViewController class and in storyboards (using @IBAction after that). 我已经看到很多在ViewController类和故事板中以编程方式创建按钮的例子(之后使用@IBAction)。

Is there a way to create a custom class for a button and to make it toggle my side menu without rewriting this action in every single ViewController. 有没有办法为按钮创建自定义类,并使其切换我的侧面菜单,而无需在每个ViewController中重写此操作。

Now I create this button on each VC I need in storyboard and copy-paste this code: 现在我在storyboard中需要的每个VC上创建此按钮并复制粘贴此代码:

@IBAction func openMenuClick() {
    sideMenuController?.toggle()
}

How can I avoid this code duplication? 如何避免此代码重复?

If this button is in every view controller in storyboard then I guess you need to connect it at some point. 如果此按钮位于故事板中的每个视图控制器中,那么我猜您需要在某个时刻连接它。

I suggest you create a subclass of UIViewController which is then a base class for all your view controllers with this button. 我建议您创建一个UIViewController的子类,然后使用此按钮为所有视图控制器创建一个基类。 You should create an outlet in base class which should then be connected in storyboard for each of the subclasses. 您应该在基类中创建一个插座,然后在故事板中为每个子类连接。

Then only the base class has this method you posted and on view did load you need to add a target manually to this method. 然后只有基类具有您发布的此方法,并且在视图上加载时您需要手动将目标添加到此方法。 I guess alternatively if the base view controller has this method as IBAction you could simply connect that one in your storyboard. 我想如果基本视图控制器将此方法作为IBAction您可以简单地在故事板中连接该方法。

In storyboard you have to create the button on navigation bar for every View Controller, now for the action of the menu button you can create an IBAction like 在故事板中,您必须在每个视图控制器的导航栏上创建按钮,现在,对于菜单按钮的操作,您可以创建类似IBAction的IBAction

extension UIViewController {

@IBAction func btnActionBack(_ sender: UIButton) {
   moveBack()
}

@IBAction func btnActionOpenSideMenu(_ sender: UIButton) {
    toggleSideMenuView()
} }

You can now drag the touchUpInside outlet of button to the IBAction btnActionOpenSideMenu . 您现在可以将按钮的touchUpInside插座拖动到IBAction btnActionOpenSideMenu I have used this for myself, also i have created a universal back button action to pop view controller 我已经为自己使用了这个,我也创建了一个通用后退按钮动作来弹出视图控制器

Create a common class for button there you can add: 为您可以添加的按钮创建一个公共类:

button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)


func buttonAction(sender: UIButton!) {   print("Button tapped") }

In your button class; 在你的按钮类中;

Swift 4: 斯威夫特4:

open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    guard let touchPoint = touches.first?.location(in: self) else { return }
    guard self.bounds.contains(touchPoint) else { return }

    // Do what you wanna do here

}

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

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