Search code examples
iosswiftbuttonuibuttonuipageviewcontroller

How can I add a button on top of a UIPageViewController?


I have a page view controller with 3 pages. I want a 'floating' button to be visible on top of all of them. I have tried using a container view for the PageView but that doesn't seem to work. How else can I get the button to remain visible across all 3 pages?

I have tried using a container view as stated in this question: UIButton across all pages of UIPageViewController


Solution

  • Alternatively to my other answer, you can add a button programmatically.

    Declare:

    let button = UIButton()
    

    and if you want, create a function called setupView()

    private func setupView() {
    
    //Here we set up the size and attributes of the button.
        currencyButton.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
        currencyButton.backgroundColor = UIColor.red
        currencyButton.setTitle("YourButtonTitle", for: .normal)
        currencyButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        self.view.addSubview(currencyButton)
    }
    

    And to use the button:

    @objc func buttonAction(sender: UIButton!) {
       //Do whatever.
       print("ButtonTapped")
    }
    

    Finally, make sure that in viewDidLoad() setupView() is called:

     override func viewDidLoad() {
        super.viewDidLoad()
    
        setupView()
    
        self.delegate = self
        configurePageControl()
        self.dataSource = self
    
    }
    

    This button will stay on screen when you scroll through the page view. Let me know if this answers your question.