RJN_WLY
RJN_WLY

Reputation: 355

Same button across all view controllers in ios app

I am developing an app with 10 view controllers, including 2 webview controllers. Every view controller contains a 'send feedback' button on top right with exactly same style and functionality. Right now, I am writing exact same code in each view controller for the buttons. I was wondering if there is a way to write the method only at one place and use it for all the buttons, since the function is same. I am using swift 3.

Upvotes: 2

Views: 1764

Answers (3)

Vijay Kumar
Vijay Kumar

Reputation: 41

You can follow this. New requirement of my project, need to show WhatsApp button across all view controller.

As above answer you should create a BaseViewController class which is Subclass of UIViewController where you create your button like this.

class BaseViewControllerUser: UIViewController {

override func viewDidLoad() {
        super.viewDidLoad()
        addWhatsAppButton()
    }

func addWhatsAppButton() {
        // Create the button
        let whatsappButton = UIButton(type: .custom)
        whatsappButton.translatesAutoresizingMaskIntoConstraints = false
        whatsappButton.setImage(UIImage(named: "ic_whatsapp"), for: .normal) // Replace with your WhatsApp icon image
        whatsappButton.addTarget(self, action: #selector(whatsappButtonTapped), for: .touchUpInside)
        
        // Add button to the view
        view.addSubview(whatsappButton)
        
        // Set constraints for the button (adjust position as needed)
        NSLayoutConstraint.activate([
            whatsappButton.widthAnchor.constraint(equalToConstant: 60),  // Set width
            whatsappButton.heightAnchor.constraint(equalToConstant: 60), // Set height
            whatsappButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), // 16 points from trailing edge
            whatsappButton.bottomAnchor.constraint(equalTo: view.centerYAnchor, constant: 0) // 100 points from bottom
        ])
    }


@objc func whatsappButtonTapped() {
        //Perform your action on this button.
    }
}

Upvotes: 0

Vasilii Muravev
Vasilii Muravev

Reputation: 3163

Create new subclass of view controller:

class SendFeedbackViewController: UIViewController {
    @IBOutlet weak var sendFeedbackButton: UIButton!

    @IBAction func sendFeedback() {
        /* do whatever you need */
    }
}

Then subclass all your view controllers from this new view controller:

class YourViewController: SendFeedbackViewController {
    /* your entire logic */
}

In storyboard set class type: enter image description here

Now you can connect your send feedback button outlet and action: enter image description here enter image description here

Upvotes: 4

Jay Patel
Jay Patel

Reputation: 2740

Use extension of UIViewController.

extension UIViewController {
   func sendFeedBack() {
     //write your code here
   }
}

And call from any ViewController.

Upvotes: 2

Related Questions